gpt4 book ai didi

python - 如果满足特定条件,则将字符串与列表列表连接起来

转载 作者:行者123 更新时间:2023-12-04 12:32:02 25 4
gpt4 key购买 nike

我有这个列表列表:

x = [["hello", 1, "pacific", 'M','F','W'], ["yes", 4, 5, "turn", 'S', 'F', 'Su']]

我想加入列表中的特定项目:'M','F','W','S','Su'

因此,如果列表中存在这些项目中的任何一项,则应将它们连接在一起,从而导致:

x = [["hello", 1, "pacific", 'M,F,W'], ["yes", 4, 5, "turn", 'S,F,Su']]

我目前的尝试是这样的:

x = [["hello", 1, "pacific", 'M','F','W'], ["yes", 4, 5, "turn", 'S', 'F', 'Su']]

z = []

for item in x:

for y in item:

if y == 'M' or y == 'F' or y =='W' or y == 'S' or y =='Su':

item.index(y)

z.append((item.index(y)))

else:
pass

x[min(z):max(z)+1] = [','.join(item[min(z):max(z)+1])]

print(x)

我想我可以在列表中获取我想要的特定字符串的位置,然后使用 min 和 max 加入它们。

我的代码返回:

[['hello', 1, 'pacific', 'M', 'F', 'W'], ['yes', 4, 5, 'turn', 'S', 'F', 'Su'], 'turn,S,F']

非常感谢任何帮助!

最佳答案

试试这个线性列表理解:

[[i for i in sublist if i not in l] + [','.join([i for i in sublist if i in l])] for sublist in x]

输出:

[['hello', 1, 'drugs', 'M,F,W'], ['yes', 4, 5, 'turn', 'S,F,Su']]

完整代码:

x = [["hello", 1, "drugs", 'M','F','W'], ["yes", 4, 5, "turn", 'S', 'F', 'Su']]
l = ['M', 'F', 'W', 'S', 'Su']
print([[i for i in sublist if i not in l] + [','.join([i for i in sublist if i in l])] for sublist in x])

这只是循环遍历列表,并在每个子列表中提取所有不在 l 列表中的字符串,并添加一个值作为最后一个元素,该元素是包含子列表中字符串的字符串它们也在 l 列表中,以逗号连接和分隔。

编辑:

由于知道特定项目不会总是在最后,您可以尝试使用 itertools.takewhileitertools.dropwhile

我稍微修改了您的列表(移动了特定项目的位置),以证明我的代码有效:

from itertools import takewhile, dropwhile
x = [["hello", 1, 'M','F','W', "drugs"], ["yes", 4, 5, 'S', 'F', 'Su', "turn"]]
l = ['M', 'F', 'W', 'S', 'Su']
newlist = []
for sublist in x:
b = list(takewhile(lambda x: x not in l, sublist))
newlist.append(b + [','.join([i for i in sublist if i in l])] + list(dropwhile(lambda x: x in l, sublist[len(b):])))
print(newlist)

输出:

[['hello', 1, 'M,F,W', 'drugs'], ['yes', 4, 5, 'S,F,Su', 'turn']]

它按预期工作。

关于python - 如果满足特定条件,则将字符串与列表列表连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68403395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com