你好,我刚刚开始学习python。
我想在列表中创建数据的每个案例
if [a,b,c,d,e]
[aa, 'ab', 'ac', 'ad', 'ae', 'ba', 'bb', 'bc', 'bd', 'be'] and so on
但我不知道该怎么做。
这是我所能做到的:
def number_of_cases(list_data):
mix_data=[]
list_data = list(map(str,list_data))
for data in list_data:
mix_data.append(data+list_data[0])
mix_data.append(data+list_data[1])
mix_data.append(data+list_data[2])
我不能继续做list[0 1 2 3 4]
因为我不知道清单会有多长......
你可以做一个平面列表理解:
data = list('abcd')
pairs = [x+y for x in data for y in data]
pairs
# ['aa', 'ab', 'ac', 'ad', 'ba', 'bb', 'bc', 'bd', 'ca', 'cb', 'cc', 'cd', 'da', 'db', 'dc', 'dd']
顺便说一句,在这个特定的例子中,甚至没有必要先列出清单
pairs = [x+y for x in 'abcd' for y in 'abcd']
也有效。
考虑使用 itertools.product
?给定两个列表,它将创建一个列表中的项目和另一个列表中的项目的所有成对组合,作为元组序列。然后将每个元组粘合在一起。
from itertools import product
data = ['a', 'b', 'c', 'd']
pairs = [''.join(x) for x in product(data, data)]
print(pairs)
@AlexL的答案是product
要走的路。下面是具有所需结果的代码的修改版本:
mix_data=[]
list_data = ['a', 'b', 'c', 'd', 'e']
list_data = list(map(str,list_data))
for data1 in list_data:
for data2 in list_data:
mix_data.append(data1+data2)
print(mix_data)
它输出:
['aa', 'ab', 'ac', 'ad', 'ae', 'ba', 'bb', 'bc', 'bd', 'be', 'ca', 'cb', 'cc', 'cd', 'ce', 'da', 'db', 'dc', 'dd', 'de', 'ea', 'eb', 'eB', 'ec', 'ed', 'ee']
你可以像 @Alex L 所说的那样使用迭代工具,也可以使用这简单的两个循环。
list1 = ['a', 'b', 'c', 'd']
nlist=[]
for x in list1:
for y in list1:
nlist+=[x+y]
print(nlist)
我的第一个建议是不正确的,如下所述。这个答案仍然是正确的。
一个可爱而简洁的方法是使用列表推导和 f 字符串(f 字符串仅在 python 3.6 及更高版本中(。例如:
chars = 'abcde'
pairs = ['{x}{y}' for x in chars for y in chars]
如果你没有 f 字符串,等效的将是这样的:
chars = 'abcde'
pairs = ([f'%s%s' % (x, y) for x in chars for y in chars])
>>>print(pairs)
['aa', 'ab', 'ac', 'ad', 'ae', 'ba', 'bb', 'bc', 'bd', 'be', 'ca', 'cb', 'cc', 'cd', 'ce', 'da', 'db', 'dc', 'dd', 'de', 'ea', 'eb', 'ec', 'ed', 'ee']