simple question on list manipulation from a newbie
John Machin
sjmachin at lexicon.net
Sun Jun 8 04:36:47 EDT 2008
On Jun 8, 4:42 pm, Sengly <Sengly.H... at gmail.com> wrote:
[snip]
> Thank you all for your help. I found a solution as the following:
The following is a solution to what?
>
> alist = [
> {'noun': 'dog', 'domestic_dog', 'Canis_familiaris'},
That is not yet valid Python. You will get a syntax error pointing to
the comma after 'domestic_dog'. Do you mean:
(1) alist = [
{'noun': ('dog', 'domestic_dog', 'Canis_familiaris')},
{'noun': ('frump', 'dog')},
# etc
]
or (2)
alist = [
('dog', 'domestic_dog', 'Canis_familiaris'),
('frump', 'dog'),
# etc
]
or (3) something else?
> {'noun': 'frump', 'dog'},
> {'noun': 'dog',},
> {'noun': 'cad', 'bounder', 'blackguard', 'dog', 'hound', 'heel'},
> {'noun': 'frank', 'frankfurter', 'hotdog', 'hot_dog', 'dog',
> 'wiener', 'wienerwurst', 'weenie'},
> {'noun': 'pawl', 'detent', 'click', 'dog'},
> {'noun': 'andiron', 'firedog', 'dog', 'dog-iron'},
> ]
>
> def getAll(alist):
> list=[]
> for i in range(0,len(alist)):
> list.extend(alist[i][:])
Note: the use of [:] to copy the contents of each element indicates
that you think that each element is a sequence (list/tuple/whatever)
i.e. option (2) above.
> return list
>
Whatever that is solving, it could be written much more clearly as:
answer = [] # don't shadow the builtin list function
# and use meaningful names
for sublist in alist:
answer.extend(sublist[:])
return answer
Aside: Why do you think you need to copy sublist? Does the plot
involve later mutation of alist?
And it can be done even more clearly using a list comprehension:
[element for sublist in alist for element in sublist]
HTH,
John
More information about the Python-list
mailing list