【问题标题】:Put results of itertools in one single list将 itertools 的结果放在一个列表中
【发布时间】:2018-08-09 20:19:29
【问题描述】:

我有这段代码,我正在尝试将 itertools 的所有结果放在一个列表中 :l = ['00','01','02','03'..],而不是我在每一行都得到一个列表['0', '0'] ['0', '1'] ['0', '2'] ['0', '3']

import itertools

for r in itertools.product('0123456789', repeat=2):
    print list(r)

【问题讨论】:

  • 为什么需要itertools?
  • list('0123456789')?
  • 不确定为什么要使用 itertools,但这是一种过度设计的方法:[el for r in itertools.product('0123456789', repeat=1) for el in r]
  • 谢谢,但在 repeat='2' 的情况下,它似乎没有返回我所期望的:l = ['00', '01', '02', ' 03' . . . ]
  • @Olivier 好吧,检查我的更新。

标签: python list itertools cartesian-product


【解决方案1】:

使用itertools 你可以这样做:

from itertools import product

list(map(''.join, product('0123456789', repeat=2)))

# ['00', '01', '02', '03', '04', '05', '06', '07', ...]

【讨论】:

  • 是的,但在 repeat=2 的情况下,我希望它返回 l = ['00' '01' '02' '03'...]
【解决方案2】:

在上面的代码中,您正在创建一个列表的每个迭代。要将元素放到一个列表中,请创建一个空列表,将项目附加到每个数组中的列表中。其实你不需要itertool 这个...

strng =  '0123456789'
num = []
for r in strng :
    num.append(r)

print(num)

但如果你真的想用itertools,你可以用这个。

import itertools as iter
num = []
for r in iter.chain('0123456789') :
    num.append(r)

print(num)

【讨论】:

  • 你不必初始化一个空列表并追加,只需执行 list(iter.chain(iterable))
猜你喜欢
  • 2023-04-07
  • 2014-05-16
  • 2017-04-06
  • 2015-02-09
  • 2022-11-18
  • 1970-01-01
  • 2016-11-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多