Как поменять местами предложение? - PullRequest
0 голосов
/ 02 августа 2020

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]
val
#[(2, 'pos:2'), (10, 'pos:10')]
x = list(zip(*val))
x
#[(2, 10), ('pos:2', 'pos:10')]

Мне нужно изменить 2,10 на 10,2 и вставить обратно в предложение

Ожидается

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

Ответы [ 5 ]

1 голос
/ 02 августа 2020

Как насчет использования замены?

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
1 голос
/ 02 августа 2020

Как насчет этого. :)

data = 'This is pos:2 and i am going to interchange with pos:10'
d = data.split() # making list
a, b = d.index('pos:2'), d.index('pos:10') # getting the index in list
d[a], d[b] = d[b], d[a] # Pythonic cool swapping
data = ' '.join(d) # joined together
print(data)

Вывод:

This is pos:10 and i am going to interchange with pos:2
1 голос
/ 02 августа 2020
data = 'This is pos:2 and i am going to interchange with pos:10'
d = data.split(' ')
position_change_1 = 2
position_change_2 = 10
temp = d[position_change_1]
d[position_change_2] = d[position_change_1]
d[position_change_2] = temp
data = ' '.join(d)
print(data)
1 голос
/ 02 августа 2020

Исходя из вашего кода, если вы хотите поменять местами только два слова, вы можете сделать что-то вроде:

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
0 голосов
/ 02 августа 2020
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))
x
#[(2, 10), ('pos:2', 'pos:10')]
x[0] = sorted(x[0],reverse=True)
y = list(zip(x[0], x[1]))
y
#[(10, 'pos:2'), (2, 'pos:10')]
data = data.split()
for i in y:
    data[i[0]]=i[1]
print(' '.join(data))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...