替换列表列表中的字符串python

时间:2018-09-23 03:40:05

标签: python list replace

我有一个包含三个单独列表的列表:

James =     ['Alvin Kamara','Alex Collins','Michael Thomas',
          'Adam Thielen','Evan Engram','Lamar Miller']

Ben =   ['Todd Gurley II','Royce Freeman','Larry Fitzgerald',
        'Cooper Kupp','Benjamin Watson','Robby Anderson']

Chris =     ['Dion Lewis','Rex Burkhead','Julio Jones',
          'Keenan Allen','Zach Ertz','Demaryius Thomas']

我想删除文本“ II”,如果您在“本”列表中查找,则会将“ Toddy Gurley II”更改为“ Todd Gurley”。我目前的尝试是这样:

master_list = [James,Ben,Chris]

for owner in master_list:
    owner = [word.replace(' II','') for word in owner]

print(master_list[1])

但是我得到的输出是:

['Todd Gurley II', 'Royce Freeman', 'Larry Fitzgerald', 'Cooper Kupp', 'Benjamin Watson', 'Robby Anderson']

4 个答案:

答案 0 :(得分:2)

您可以使用re

import re
print([re.sub('\sII$', '', i) for i in master_list[1]])

输出:

['Todd Gurley', 'Royce Freeman', 'Larry Fitzgerald', 'Cooper Kupp', 'Benjamin Watson', 'Robby Anderson']

答案 1 :(得分:1)

在外部for循环中,您将更新owner变量的副本,但不要在列表中替换它。您可以改为将更新后的owner变量添加到新列表中:

new_list = []
for owner in master_list:
    owner = [word.replace(' II','') for word in owner]
    new_list.append(owner)

print(new_list[1])

['Todd Gurley', 'Royce Freeman', 'Larry Fitzgerald', 'Cooper Kupp', 'Benjamin Watson', 'Robby Anderson']

或者,您可以在所有者列表上使用enumerate(),以更新原始的master_list

for i, owner in enumerate(master_list):
    owner = [word.replace(' II','') for word in owner]
    master_list[i] = owner

print(master_list[1])

['Todd Gurley', 'Royce Freeman', 'Larry Fitzgerald', 'Cooper Kupp', 'Benjamin Watson', 'Robby Anderson']

答案 2 :(得分:1)

当您致电owner = [word.replace(' II','') for word in owner]时,您没有更新master_list;您正在修改其元素之一的副本。

您可以通过拨打

之类的电话来循环并更新master_list
master_list[1] = [word.replace(' II','') for word in owner]

或者您可以引用一个新数组:

new_master_list = []
for owner in master_list:
    new_master_list.append([word.replace(' II', '') for word in owner])

print(new_master_list[1])

答案 3 :(得分:1)

我们可以在此处组合枚举列表理解并使用字符串的[-2:]位置进行评估

l = [James, Ben, Chris]

for idx, item in enumerate(l):
    l[idx] = [i[:-3] if 'II' in i[-2:] else i for i in item]
chrx@chrx:~/python/stackoverflow/9.22$ python3.7 uk.py
[['Alvin Kamara', 'Alex Collins', 'Michael Thomas', 'Adam Thielen', 'Evan 
Engram', 'Lamar Miller'], ['Todd Gurley', 'Royce
Freeman', 'Larry Fitzgerald', 'Cooper Kupp', 'Benjamin Watson', 'Robby
Anderson'], ['Dion Lewis', 'Rex Burkhead', 'Julio Jones', 'Keenan
Allen', 'Zach Ertz', 'Demaryius Thomas']]