猿问

Python通过成功地重复现有的字符串元素来创建一个新列表

我有一个清单。我想通过为每个元素添加一个共同点来重复这些元素。


main_list = ['lst1','lst2','lst3']  # existing list


new_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)]

有更好的方法吗?


天涯尽头无女友
浏览 150回答 1
1回答

守着星空守着你

您可以简单地使用嵌套循环: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 productmain_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']
随时随地看视频慕课网APP

相关分类

Python
我要回答