cuốn sách gpt4 ai đã làm

python - 从列表字典创建 n 个嵌套循环

In lại Tác giả: Walker 123 更新时间:2023-11-28 21:52:56 25 4
mua khóa gpt4 Nike

我有一个有 n 个键的字典,每个键包含一个 n 个字符串的列表。

我想遍历字符串的每个组合,生成键和与之关联的字符串。

这是一个有 3 个键的字典的例子,但我想概括为一个有 n 个键的字典。

dict = {'key1':['str0','str1','str2','strn'],'key2':['apples','bananas','mangos'],'key3':['spam','eggs','more spam']}

for str1 in dict['key1']:
for str2 in dict['key2']:
for str3 in dict['key3']:
print 'key1'+"."+str1,'key2'+"."+str2,'key3'+"."+str3

请在回答问题时描述一下答案是如何工作的,因为我是 python 的新手,还不知道所有可用的工具!

预期输出:

key1.str0 key2.apples key3.spam
key1.str0 key2.apples key3.eggs
key1.str0 key2.apples key3.more spam
key1.str0 key2.bananas key3.spam
key1.str0 key2.bananas key3.eggs
...

n 维迭代器的预期输出:

key1.str0 key2.apples key3.spam ... keyn.string0
key1.str0 key2.apples key3.spam ... keyn.string1
key1.str0 key2.apples key3.spam ... keyn.string2
...
key1.str0 key2.apples key3.spam ... keyn.stringn
...

câu trả lời hay nhất

bạn nên sử dụng itertools.product , 它执行 Cartesian product ,这是您要尝试执行的操作的名称。

from itertools import product

# don't shadow the built-in name `dict`
d = {'key1': ['str0','str1','str2','strn'], 'key2': ['apples','bananas','mangos'], 'key3': ['spam','eggs','more spam']}

# dicts aren't sorted, but you seem to want key1 -> key2 -> key3 order, so
# let's get a sorted copy of the keys
keys = sorted(d.keys())
# and then get the values in the same order
values = [d[key] for key in keys]

# perform the Cartesian product
# product(*values) means product(values[0], values[1], values[2], ...)
results = product(*values)

# each `result` is something like ('str0', 'apples', 'spam')
for result in results:
# pair up each entry in `result` with its corresponding key
# So, zip(('key1', 'key2', 'key3'), ('str0', 'apples', 'spam'))
# yields (('key1', 'str0'), ('key2', 'apples'), ('key3', 'spam'))
# schematically speaking, anyway
for key, thing in zip(keys, result):
print key + '.' + thing,
print

请注意,我们没有在任何地方对字典中的键数进行硬编码。如果你使用 collections.OrderedDict,你可以避免排序的东西而不是 mệnh lệnh.


如果您希望将键附加到它们的值,这是另一种选择:

from itertools import product

d = {'key1': ['str0','str1','str2','strn'], 'key2': ['apples','bananas','mangos'], 'key3': ['spam','eggs','more spam']}

foo = [[(key, value) for value in d[key]] for key in sorted(d.keys())]

results = product(*foo)
for result in results:
for key, value in result:
print key + '.' + value,
print

在这里,我们构建了一个包含(键,值)元组列表的列表,然后将笛卡尔积应用于列表。这样,键和值之间的关系完全包含在 results 中。想想看,这可能比我发布的第一种方式要好。

关于python - 从列表字典创建 n 个嵌套循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27518641/

25 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress