简体   繁体   中英

python generators in lists can't use it

I have created a list like this:

z=[5,4]

and I need to assign this list values to another lists and set the elements of z list to the first elements of that lists so I do so :

other.append([i,0,'tweak'] for i in z)

but it keeps generate something like that :

[<generator object <genexpr> at 0x024B7F30>, <generator object <genexpr> at 0x02562288>]

I could not use my other list at this form !

i expected that my other list look like :

[[5,0,'tweak'][4,0,'tweak']]

[i,0,'tweak'] for i in z is a generator expression. There is no explicit iterable type declared (list which is denoted by square brackets [l1, l2] ) - interpreter detects it and creates object which computes values on demand - a generator.

If you want to create list, you must declare it explicitly.

other.append([[i,0,'tweak'] for i in z])  # appends list, not generator

Notes:

  • [i,0,'tweak'] for i in z creates a generator function and not a List Comprehension to convert it you could add brackets ie [[i,0,'tweak'] for i in z]
  • Now coming to the second problem when first is rectified [[i,0,'tweak'] for i in z] creates a lists of list [[LOL]] and when you append into a list it becomes lists of lists of list [[[LOLOL]]] to avoid that you can use append

You could do this

Code:

z=[5,4]
other=[]
other.extend([[i,0,'tweak'] for i in z])
print other

This ?

z=[5,4]
other = [] # or some list
other += [[i,0,'tweak'] for i in z]

You shouldn't be using append at all here, since you want to construct your list directly. Just use a list comprehension:

other = [[i,0,'tweak'] for i in z]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM