Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在字符串python数组中使用条件对单词重新排序_Python_Arrays_Regex_List_Sorting - Fatal编程技术网

在字符串python数组中使用条件对单词重新排序

在字符串python数组中使用条件对单词重新排序,python,arrays,regex,list,sorting,Python,Arrays,Regex,List,Sorting,在找到特定字符/单词后,我需要更改句子中单词的顺序 例如: s = ["i", "dont", "like, "you"] 如果找到dont,则顺序如下: s_order = ["dont", "like", "you", "i"] s_sorted = sorted(s, key=lambda x:(x!='dont', x)) dont之前的所有单词将添加/追加到最后一个单词中 我已经尝试使用如下排序方法: s_order = ["dont", "like", "you", "i"]

在找到特定字符/单词后,我需要更改句子中单词的顺序

例如:

s = ["i", "dont", "like, "you"]
如果找到
dont
,则顺序如下:

s_order = ["dont", "like", "you", "i"]
s_sorted = sorted(s, key=lambda x:(x!='dont', x))
dont
之前的所有单词将添加/追加到最后一个单词中

我已经尝试使用如下排序方法:

s_order = ["dont", "like", "you", "i"]
s_sorted = sorted(s, key=lambda x:(x!='dont', x))
但是
前面的单词不
附加在前面而不是最后:

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']

你可以很容易地做到这一点

s = ["i", "dont", "like", "you"]
split_target = "dont" 
split_idx = -1

for word_idx in range(len(s)):
     if s[word_idx] == split_target:
         split_idx = word_idx

s = s[split_idx:] + s[:split_idx]
这段代码的作用是找到拆分列表的位置,然后将列表从那里一直提取到最后,并将其从开始到拆分点添加到另一个列表中

尝试使用:

>>> l = s[s.index('dont'):]
>>> l + s[:len(s) - len(l)]
['dont', 'like', 'you', 'i']
>>> 

您也可以为此目的使用一个具有内置旋转方法的deque。它找到
dont
所在的位置,并根据索引对其进行旋转。向左旋转是用负索引完成的,因此
-d.index('dont')

输出

deque(['dont', 'like', 'you', 'i'])

一种可能的解决方案是使用
sorted()


谢谢你的帮助和对代码的解释:D
['dont', 'like', 'you', 'i']