我想用某些单词替换列表中的值。
acts = []
act = input('Acts: ')
acts.append(act.split())
change = input('Change: ')
while change:
if 'Scratch' in change:
所以基本上,我有一个行为列表,如果命令(更改)包含单词scratch,那么我用“scratch”一词替换列表中的act,我不希望它的顺序价值要改变。
如何用列表中的刮擦字替换命令的第二个字(更改)?
示例:
Acts: Cynthia Edward Princess Natasha Shehabi Back-To-Front
Change: Scratch Natasha
Change: Scratch Edward
Change:
Cynthia -SCRATCHED- Princess -SCRATCHED- Shehabi Back-To-Front
答案 0 :(得分:0)
这假设“更改”的输入将包含由空格分隔的2个单词。
acts = input('Acts: ').split()
while True:
change = input('Change: ')
if not change:
break
_to, _from = change.split()
for i, act in enumerate(acts):
if act == _from:
acts[i] = _to
print(' '.join(acts))
答案 1 :(得分:0)
acts = ['Cynthia', 'Edward', 'Princess', 'Natasha', 'Shehabi' ,'Back-To-Front']
print "Acts: {}".format(" ".join(acts))
change = raw_input('Change: ')
while (change.strip() != ''):
if 'Scratch' in change:
act = change.replace('Scratch','').strip()
if act in acts:
acts[acts.index(act)] = '-SCRATCHED-'
change = raw_input('Change: ')
print " ".join(acts)