这是我的第一个 python 程序。我使用以下代码生成给定范围的组合。
for k in range(0, items+1):
for r in range(0, items+1):
if (r-k) > 0:
res = [x for x in itertools.combinations(range(k, r), r-k)]
print res
假设 items=4,代码产生 10 种组合
#
# [(0,)]
# [(0, 1)]
# [(0, 1, 2)]
# [(0, 1, 2, 3)]
# [(1,)]
# [(1, 2)]
# [(1, 2, 3)]
# [(2,)]
# [(2, 3)]
# [(3,)]
#
我的问题是
(a) 如何检索每个组合中的每个元素,比方说,在 [(1, 2, 3)] 中,如何检索偏移量 0(即 1)处的值?
(b) 如何将 itertools.combinations 的返回值存储到“res”中的列表数组中(例如,res[0] = [(0,)] 、res[1] = [(0 , 1)] ?
(c) 假设我想使用 map(),如何将值例如 [(0, 1)] 作为键,并为该键分配一个随机值?
最佳答案
a) 使用索引:
>>> [(1, 2, 3)][0][0] 1
b) 我不是 100% 理解这个问题,但是您可以使用
list(itertools.combinations(...))
c) 我认为您误解了
map()
的作用。map(str, [1, 2, 3])
等同于:[str(i) for i in [1, 2, 3]]
如果你想给[(0, 1)]
一个值,你可以使用字典,但是你必须使用(0, 1)
而不是[(0, 1)]
因为否则你会得到 TypeError: unhashable type: 'list'
。如果你想要一个“随机值”,我想你可以使用 random
模块:
import random
{(0, 1) : random.randint(1,10)} # This is just an example, of course
要将所有输出存储在一个列表中,您可以使用大量列表理解:
>>> [list(itertools.combinations(range(x, i), i-x)) for x in range(0, items+1) for i in range(0, items+1) if (i-x) > 0]
[[(0,)], [(0, 1)], [(0, 1, 2)], [(0, 1, 2, 3)], [(1,)], [(1, 2)], [(1, 2, 3)], [(2,)], [(2, 3)], [(3,)]]
关于python - 在 Python 中提取列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17290518/