我有一个清单。我想通过为每个元素添加一个共同点来重复这些元素。main_list = ['lst1','lst2','lst3'] # existing listnew_list = ['lst1_mean','lst1_std','lst2_mean','lst2_std','lst3_mean','lst3_std'] # expected list我的代码:aux_list1 = [i+'_mean' for i in main_list]aux_list2 = [i+'_std' for i in main_list]new_list = [i,j for i,j in zip(aux_list1,aux_list2)]有更好的方法吗?
1 回答
守着星空守着你
TA贡献1799条经验 获得超8个赞
您可以简单地使用嵌套循环:
main_list = ['lst1', 'lst2', 'lst3']
suffixes = ['_mean', '_std']
new_list = [w + s for w in main_list for s in suffixes]
print(new_list)
输出:
['lst1_mean', 'lst1_std', 'lst2_mean', 'lst2_std', 'lst3_mean', 'lst3_std']
您还可以使用itertools.product(具有可变深度嵌套循环的概念):
from itertools import product
main_list = ['lst1', 'lst2', 'lst3']
suffixes = ['_mean', '_std']
new_list = [''.join(w) for w in product(main_list, suffixes)]
print(new_list)
输出:
['lst1_mean', 'lst1_std', 'lst2_mean', 'lst2_std', 'lst3_mean', 'lst3_std']
添加回答
举报
0/150
提交
取消