![](/img/trans.png)
[英]In Python, when iterating through items in list, how to start at 0 if end is reached?
[英]How to remove None when iterating through a list in python
我有这两个不相等的列表,我正在使用 itertools 循环遍历它们,我正在尝试使用过滤器函数删除 List1 中生成的 None 以便在一天结束时 a 只包含两个元素而不是三个(计数无)但我不断收到此错误:类型错误:NoneType 对象不可迭代
import itertools
List1 = [['a'],['b']]
List2 = ['A','b','C']
l = list(itertools.chain(*List1))
print(l)
for a, b in itertools.zip_longest((b for a in List1 for b in a),List2):
filter(None, a)
print(a,b)
为什么不直接使用zip
?
for a, b in zip((b for a in List1 for b in a),List2):
print(a,b)
但是,如果您真的坚持使用zip_longest
,则不需要使用filter
来删除 None 值。 你只需要一个if
。
for a, b in itertools.zip_longest((b for a in List1 for b in a),List2):
if a is None: continue
print(a,b)
不完全清楚你想要什么。 据我了解问题和评论,您想使用izip_longest
来组合列表,但结果中没有任何None
元素。
这将从列表的压缩“切片”中过滤None
并仅打印非None
值。 但是请注意,通过这种方式您无法确定例如non_none
列表中的第一个元素是来自第一个列表还是第二个或第三个。
a = ["1", "2"]
b = ["a", "b", "c", "d"]
c = ["x", "y", "z"]
for zipped in izip_longest(a, b, c):
non_none = filter(None, zipped)
print non_none
输出:
('1', 'a', 'x')
('2', 'b', 'y')
('c', 'z')
('d',)
顺便说一句,你的filter(None, a)
做了什么:它从你的a
过滤None
值,即从字符串"a"
和"b"
(它没有做太多,因为它们不包含None
值),直到它失败对于最后一个值,因为None
不可迭代。 此外,它无论如何都会丢弃结果,因为您没有将其绑定到变量。 filter
不会改变原来的列表,但返回过滤副本!
import itertools as it
def grouper(inputs, n, fillvalue=None):
iters = [iter(inputs)] * n
interim = it.zip_longest(*iters, fillvalue=fillvalue)
return interim
nums = range(23)
results = (list(grouper(nums, 4)))
finalanswer = []
for zipped in results:
# non_none = tuple(filter(None, zipped))
# unfortunately the line above filters 0 which is incorrect so instead use:
non_none = tuple(filter(lambda x: x is not None, zipped))
finalanswer.append(non_none)
print(finalanswer)
上面的代码使用 zip_longest 来说明生成 'n' 个列表的压缩迭代,而不管给定列表中是否存在相应的条目 --- 然后去掉 'None' 值 --- 注意 FILTER 考虑 None 和 0等价的,所以你必须使用“lambda”版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.