【问题标题】:How to get the value in a nested list using itertools.zip_longest如何使用 itertools.zip_longest 获取嵌套列表中的值
【发布时间】:2015-06-12 16:41:36
【问题描述】:

我有两个列表,我想使用 itertool.zip_longest 来比较列表中的一些值并执行其他操作,这是我到目前为止编写的代码

import itertools

List1  = [['a'],['B']]
List2 = ['A','b','C']

for a in List1:
    for i in itertools.zip_longest(a,List2):
        print (i)

但这是我得到的结果,我仍在努力解决这种行为

('a', 'A')
(None, 'b')
(None, 'C')
('B', 'A')
(None, 'b')
(None, 'C')

我正在尝试得到这样的东西

('a', 'A')
('B', 'b')
(None, 'C')

所以我可以直接比较值

【问题讨论】:

  • 不清楚为什么您期望第二个输出。如果你想这样,List1 应该看起来像 ['a', 'B'] - 也许先把它弄平?
  • 对不起,我还是 python 的新手,我想我想先用第一个 for 循环来扁平化(即获取列表中的值)

标签: python-3.x for-loop itertools


【解决方案1】:

您可以使用生成器表达式来展平 list1:

List1  = [['a'],['B']]
List2 = ['A','b','C']

print(list(itertools.zip_longest((b for a in List1 for b in a),List2))
[('a', 'A'), ('B', 'b'), (None, 'C')]

如果你想比较只是迭代 zip_longest 对象解包:

for a, b in itertools.zip_longest((b for a in List1 for b in a),List2):
    if a == b:
        # do whatever

要设置特定的默认值,请使用 fillvalue:

List1  = [['a'],['B']]
List2 = ['A','b','C']

print(list(itertools.zip_longest((b for a in List1 for b in a),List2,fillvalue="foo")))
[('a', 'A'), ('B', 'b'), ('foo', 'C')]

【讨论】:

  • 如何删除第三个元组中的 None 或者更好地为其设置默认值
  • @danidee,在 zip_longest 中指定 fillvalue=whatever
【解决方案2】:

对于该结果,您需要展平列表a,您可以使用itertools.chain

>>> list(itertools.izip_longest(itertools.chain(*List1),List2))
[('a', 'A'), ('B', 'b'), (None, 'C')]

【讨论】:

  • 感谢您的快速回复,但我认为我需要展平 list1 以获得 ['a','B'] 以便我可以像这样比较:如果 List2 中的 List1[0]: do_something() 或者有什么方法可以比较值
  • itertools.chain(*List1) 为您展平列表。
  • @danidee 欢迎!正如 achampio 所说,itertools.chain(*List1) 使列表变平!
  • 如何删除第三个元组中的 None 或者更好地为其设置默认值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-25
  • 2023-03-28
  • 2021-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多