dev_a = [[True, 1, 2, 3], [False, 1, 2, 3], [True, 1, 2, 3]]
dev_b = []
My goal is to iterate over nested lists in dev_a
and check if [0]
is True
or False
. I need the nested list in dev_b
, when [0]
is False
.
My approach was the following:
if (x[0] for x in dev_a) is False:
?
I don't know what to tell the machine, that it will copy the whole dataset.
I need it like this, when it's done:
dev_a = [[True, 1, 2, 3], [False, 1, 2, 3], [True, 1, 2, 3]]
dev_b = [False, 1, 2, 3]
what you want is this:
dev_a = [[True, 1, 2, 3], [False, 1, 2, 3], [True, 1, 2, 3]]
dev_b = [x for x in dev_a if x[0] == False]
take note though, this will be dynamic depending on your input. So you could end up with a single array, or multiple.
for sublist in dev_a:
if not sublist[0]:
dev_b.append(sublist)
Something like this?
If you want dev_b to be a flat list, use extend
for sublist in dev_a:
if not sublist[0]:
dev_b.extend(sublist)
You could just use filter
dev_a = [[True, 1, 2, 3], [False, 1, 2, 3], [True, 1, 2, 3]]
dev_b = list(filter(lambda l: l[0] is False, dev_a))
print(dev_b)
Result:
[[False, 1, 2, 3]]
Use next()
instead of list()
if you want just one result instead of a list of lists.
try
dev_a = [[True, 1, 2, 3], [False, 1, 2, 3], [True, 1, 2, 3]]
dev_b = [e for e in dev_a if e[0] is False]
print(dev_b)
output
[[False, 1, 2, 3]]
If you want a flattened list
# filter only the inner items you want using filter function
outer = list(filter(lambda a: a[0] == False, dev_a))
# or without using filter
outer = [a for a in dev_a if not a[0]]
# flatten all items
x = [item for inner in outer for item in inner]
Result:
[False, 1, 2, 3]
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.