找到特定字符/单词后,我需要更改句子中的顺序单词
例s = ["i", "dont", "like, "you"]
如果找到dont
,则命令如下s_order = ["dont","like","you","i"]
dont
之前的所有单词都将添加/添加到最后一个单词中
我已经尝试使用像这样的排序方法s_sorted = sorted(s, key=lambda x:(x!='dont', x))
但是dont
之前的单词先附加而不是最后附加s_sorted = ['dont', 'i', 'like', 'you']
有没有最好的方法做到这一点?谢谢
谢谢你的帮助
最佳答案
使用简单切片:
s = ["i", "dont", "like", "you"]
pos = s.index('dont') # the position of the search word in sequence
res = s[pos:] + s[:pos]
print(res) # ['dont', 'like', 'you', 'i']
关于python - 使用字符串python数组中的条件对单词进行重新排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57346357/