Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.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 - Fatal编程技术网

Python 如何颠倒句子中的位置?

Python 如何颠倒句子中的位置?,python,Python,data='这是pos:2,我将与pos:10进行交换' 代码如下 val = [(i,v) for i,v in enumerate(data.split()) if ':' in v] val #[(2, 'pos:2'), (10, 'pos:10')] x = list(zip(*val)) x #[(2, 10), ('pos:2', 'pos:10')] 我需要倒转2,10到10,2,然后插入到句子后面 预料之外 data='这是pos:10,我将与pos:2进行交换'根据您的代码

data='这是pos:2,我将与pos:10进行交换'

代码如下

val = [(i,v) for i,v in enumerate(data.split()) if ':' in v]
val
#[(2, 'pos:2'), (10, 'pos:10')]
x = list(zip(*val))
x
#[(2, 10), ('pos:2', 'pos:10')]
我需要倒转2,10到10,2,然后插入到句子后面

预料之外


data='这是pos:10,我将与pos:2进行交换'

根据您的代码,如果您只想交换两个单词,您可以执行以下操作:

data = 'This is pos:2 and i am going to interchange with pos:10'

val = [(i,v) for i,v in enumerate(data.split()) if ':' in v]
x = list(zip(*val))

new_data = ''
for item in data.split(" "):
    if ":" in item:
        num2select = None
        if str(x[0][0])==item.split(":")[1]:
            num2select = x[0][1]
        else:
            num2select = x[0][0]
        new_data+=item.split(":")[0] + ":" + str(num2select) + " "
    else:
        new_data+=item+" "

print(new_data)
输出:

This is pos:10 and i am going to interchange with pos:2
This is pos:10 and i am going to interchange with pos:2
This is pos:10 and i am going to interchange with pos:2
这个怎么样

输出:

This is pos:10 and i am going to interchange with pos:2
This is pos:10 and i am going to interchange with pos:2
This is pos:10 and i am going to interchange with pos:2

用“替换”怎么样

data = 'This is pos:2 and i am going to interchange with pos:10'

st1 = 'pos:2'
st2 = 'pos:10'
st_temp = 'pos:Temp'

data1 = data.replace(st1,st_temp).replace(st2,st1).replace(st_temp,st2)

print(data1)
输出:

This is pos:10 and i am going to interchange with pos:2
This is pos:10 and i am going to interchange with pos:2
This is pos:10 and i am going to interchange with pos:2