I want to append items to an existing list that have been generated by list comprehension as individual lists.
source = [1,2,3,4,5]
I want the result to look like [[2], [4]]
I have tried the following (and other crazy combos of '[]' and '()' and gotten nowhere)...
target = []
target.append([r for r in source if r == 2 or r == 4])
print(target)
[[2, 4]]
target = []
target.append([[r] for r in source if r == 2 or r == 4])
print(target)
[[[2], [4]]]
target = []
target.append([r] for r in source if r == 2 or r == 4)
print(target)
[<generator object <genexpr> at 0x0000022F1986E4C8>]
You can use .extend()
instead of .append()
:
source = [1, 2, 3, 4, 5]
target = []
target.extend([r] for r in source if r == 2 or r == 4)
print(target)
# [[2], [4]]
It's possible to use .extend()
in this case because it receives an iterable as an argument.
Just do this list comprehension with extend
:
target.extend([[r] for r in source if r in [2, 4]])
And now target
would be:
[[2], [4]]
您可以改用list.extend
方法:
target.extend([r] for r in source if r == 2 or r == 4)
Instead of .append()
go for .extend
:
source = [1,2,3,4,5]
target=[]
target.extend([t] for t in source if t==2 or t==4)
print(target)
Just do this
source = [1,2,3,4,5]
target = [[r] for r in source if r==2 or r==4]
print(target)
# output: [[2], [4]]
If the target list is not empty and you want to append new values, you can try this
source = [1,2,3,4,5]
target = [[7],[8]]
target.extend([[r] for r in source if r==2 or r==4])
print(target)
# output: [[7], [8], [2], [4]]
or
source = [1,2,3,4,5]
target = [[7],[8]]
target += [[r] for r in source if r==2 or r==4]
print(target)
# output: [[7], [8], [2], [4]]
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.