假设我在我的 pytn 脚本中有 2 个列表:
my_list = ['hat', 'bat']
other_list = ['A', 'B', 'C']
我想遍历other_list
并为 'bat' 创建一个嵌套列表,将 '_' + other_list 项目添加到 'bat' 并将其放入嵌套列表中:
for item in other_list:
for thing in my_list:
if thing == 'bat':
print(thing + '_' + item)
我想要的结果将是 new_list = ['hat',['bat_A','bat_B','bat_C']] 我将如何实现这一点?
new_list = []
extra = []
for item in other_list:
for thing in my_list:
if thing == 'bat':
extra.append(thing + '_' + item)
else:
new_list.append(thing)
new_list.append(extra)
试试这个:
>>> my_list = ['hat', 'bat']
>>> other_list = ['A', 'B', 'C']
>>> new_list=[my_list[0], [f'{my_list[1]}_{e}' for e in other_list]]
>>> new_list
['hat', ['bat_A', 'bat_B', 'bat_C']]
如果你的问题(有点不清楚)只是对'bat'
做出不同的反应,你可以这样做:
my_list = ['hat', 'bat','cat']
other_list = ['A', 'B', 'C']
new_list=[]
for e in my_list:
if e=='bat':
new_list.append([f'{e}_{x}' for x in other_list])
else:
new_list.append(e)
>>> new_list
['hat', ['bat_A', 'bat_B', 'bat_C'], 'cat']
可以简化为:
>>> [[f'{e}_{x}' for x in other_list] if e=='bat' else e for e in my_list]
['hat', ['bat_A', 'bat_B', 'bat_C'], 'cat']
我认为将工作
my_list = ['hat', 'bat']
other = ['A', 'B' , 'C']
new_list = []
extra = []
for item in my_list:
if item == 'bat':
for char in other:
extra.append(item + '_' + char)
else:
new_list.append(item)
new_list.append(extra)
print(new_list)
OK,这只是我的答案,但它似乎工作。我认为是笨重的,虽然,我希望有一个更好的答案
my_list = ['hat', 'bat']
other_list = ['A', 'B', 'C']
new_list = []
extra = []
for item in other_list:
for thing in my_list:
if thing == 'bat':
extra.append(thing + '_' + item)
else:
if thing not in new_list:
new_list.append(thing)
new_list.append(extra)
本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处
评论列表(70条)