How to create a list by concatenating two list using python
如何通过使用python连接两个列表来创建列表
1 2 | Var=['Age','Height'] Cat=[1,2,3,4,5] |
我的输出应该如下所示。
1 2 | AgeLabel=['Age1', 'Age2', 'Age3', 'Age4', 'Age5'] HeightLabel=['Height1', 'Height2', 'Height3', 'Height4', 'Height5'] |
结合听写理解和列表理解:
1 2 3 4 5 | >>> labels = 'Age', 'Height' >>> cats = 1, 2, 3, 4, 5 >>> {label: [label + str(cat) for cat in cats] for label in labels} {'Age': ['Age1', 'Age2', 'Age3', 'Age4', 'Age5'], 'Height': ['Height1', 'Height2', 'Height3', 'Height4', 'Height5']} |
试试这个:
1 2 3 4 5 | Var=['Age','Height'] Cat=[1,2,3,4,5] for i in Var: c = [(i+str(y)) for y in Cat] print (c) #shows as you expect |
简洁明了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Var=['Age','Height'] Cat=[1,2,3,4,5] AgeLabel = [] HeightLabel= [] for cat_num in Cat: current_age_label = Var[0] + str(cat_num) current_height_label = Var[1] + str(cat_num) AgeLabel.append(current_age_label) HeightLabel.append(current_height_label) print(AgeLabel) print(HeightLabel) |
产量
1 2 | AgeLabel= ['Age1', 'Age2', 'Age3', 'Age4', 'Age5'] HeightLabel= ['Height1', 'Height2', 'Height3', 'Height4', 'Height5'] |
1 2 3 4 | Var=['Age','Height'] Cat=[1,2,3,4,5] from itertools import product print(list(map(lambda x:x[0]+str(x[1]),product(Var,Cat)))) |
这将为您提供以下输出。
1 | ['Age1', 'Age2', 'Age3', 'Age4', 'Age5', 'Height1', 'Height2', 'Height3', 'Height4', 'Height5'] |
您可以根据需要拆分列表。
您可以将第二个列表元素视为通过循环遍历两个列表来连接字符串的字符串。维护字典以存储值。
1 2 3 4 5 6 7 8 9 | Var=['Age','Height'] Cat=[1,2,3,4,5] label_dict = {} for i in var: label = [] for j in cat: t = i + str(j) label.append(t) label_dict[i+"Label"] = label |
在最后的标签上
1 | label_dict = {AgeLabel:['Age1', 'Age2', 'Age3', 'Age4', 'Age5'],HeightLabel:['Height1', 'Height2', 'Height3', 'Height4', 'Height5']} |