a = ["I like apple","I love you so much"]
我想用以下内容改变“苹果”和“爱”字:“橙色”,“喜欢” 但是我不想改变元素(句子),所以输出必须是
a= ["I like orange","I like you so much"]
除了orange
和like
之外的任何内容都不会发生任何变化。甚至没有添加或删除空间。
答案 0 :(得分:1)
您可以使用字典进行映射:
public function addUser($key)
{
array_push(self::$users, $key);
}
然后,提供word_mapping = {
'apple': 'orange',
'love': 'like'
}
:
list of strings
e.g:
def translate(text):
return reduce(lambda x, y: x.replace(y, word_mapping[y]), word_mapping, text)
def translate_all(text_list):
return [translate(s) for s in text_list]
答案 1 :(得分:0)
您可以使用:
a[0].replace('apple', 'orange')
a[1].replace('love', 'like')
答案 2 :(得分:0)
如果你想保持原样,试试这个,
>>> a = ["I like apple","I love you so much"]
>>> [i.replace('apple','orange').replace('love','like') for i in a]
['I like orange', 'I like you so much']
>>>
答案 3 :(得分:0)
apple
或单词love
并相应地将其替换为orange
或like
并将列表返回给你。
[(i.replace("apple","orange") or i.replace("love","like")) for i in a]
这是执行
>>> a = ["I like apple","I love you so much"]
>>> [(i.replace("apple","orange") or i.replace("love","like")) for i in a]
['I like orange', 'I love you so much']
答案 4 :(得分:0)
字符串在Python中是不可变的,即无法修改 所以,像
这样的电话a[0].replace("apple","orange")
将返回一个新字符串,而不是更改列表的原始元素。
a[0]=a[0].replace("apple","orange")
这应该可以胜任。
答案 5 :(得分:0)
replace_map = [
('apple', 'orange'),
('love', 'like')
]
def replace_all(s, m):
for k, v in m:
s = s.replace(k, v)
return s
b = [replace_all(s, replace_map) for s in a]
答案 6 :(得分:0)
Patrick Haugh,Sudheesh Singanamalla和Mohideen ibn Mohammed所提出的列表理解用途可能是更加pythonic的方式...... 一步一步,而不是pythonic是:
>>> a = ["I like apple","I love you so much"]
>>> for i in xrange(len(a)):
... if a[i].find('apple') is not -1:
... a[i]=a[i].replace('apple','orange')
... if a[i].find('love') is not -1:
... a[i]=a[i].replace('love','like')
...
>>> a
['I like orange', 'I like you so much']
或更直接:
>>> for i in xrange(len(a)):
... a[i]=a[i].replace('apple','orange')
... a[i]=a[i].replace('love','like')
...
>>> a
['I like orange', 'I like you so much']