删除第二个列表中第一个出现的单词?

时间:2018-05-28 09:55:04

标签: python python-3.x list

我有一个像这样的列表

[['a', 'word'],
['University', 'org'],
['of', 'org'],
['Michigan', 'org'], 
['Michigan', 'country']]

我想做的是如果我在第一次迭代时找到密歇根这个词,我将返回标签,我将用"删除"当我再次迭代时,我应该找到像这样的列表

[['a', 'word'],
['University', 'org'],
['of', 'org'],
['deleted', 'org'],
['Michigan', 'country']]

我尝试的是

for i in range(len(list)):

    if word.lower()==list[i][0].lower():
        found= list[i][1]

        list.pop(i)
        list[i][0] = "deletedword"


        break

3 个答案:

答案 0 :(得分:3)

使用生成器表达式查找第一个"Michigan"的位置。将其替换为必填字词:

lst = [['a', 'word'], ['University', 'org'], ['of', 'org'], ['Michigan', 'org'], ['Michigan', 'country']]

try:
    pos = next((i, x.index('Michigan')) for i, x in enumerate(lst) if 'Michigan' in x)
    lst[pos[0]][pos[1]] = 'deleted'

except StopIteration:
    print('There is no Michigan in the list')

print(lst)

# [['a', 'word'], 
#  ['University', 'org'], 
#  ['of', 'org'], 
#  ['deleted', 'org'], 
#  ['Michigan', 'country']]

答案 1 :(得分:1)

l = [['a', 'word'], ['University', 'org'], ['of', 'org'], ['Michigan', 'org'], ['Michigan', 'country']]

toReplace = 'Michigan'
for i in l:
    if i[0].lower() == toReplace.lower():
        i[0] = "deletedword"    #No need to Pop just replace.
        break
print(l)

<强>输出:

[['a', 'word'], ['University', 'org'], ['of', 'org'], ['deletedword', 'org'], ['Michigan', 'country']]

答案 2 :(得分:0)

您希望break退出嵌套for循环。一种可读的方法是使用函数和return语句:

def remove_first_el(A, k='Michigan'):
    for i in range(len(A)):                         # iterate outer lists
        for j in range(len(A[i])):                  # iterate inner lists
            if A[i][j].casefold() == k.casefold():  # ignore case for comparison
                A[i][j] = 'deleted'
                return A

res = remove_first_el(lst)

print(res)

[['a', 'word'],
 ['University', 'org'],
 ['of', 'org'],
 ['deleted', 'org'],
 ['Michigan', 'country']]

如果你需要&#34;密歇根&#34;在子列表的第一个元素中,您可以相应地修改您的函数:

def remove_first_el_zero_pos(A, k='Michigan'):
    for i in range(len(A)):
        if A[i][0].casefold() == k.casefold():
            A[i][0] = 'deleted'
            return A