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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (39)

我有这样的列表

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

我想要做的是如果我在第一次迭代时发现michigan这个词,我将返回标签,并且将用“已删除”等内容代替该词,当我再次迭代时,我应该找到像这样的列表

[['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
提问于
用户回答回答于
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']]
用户回答回答于
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']]

扫码关注云+社区

领取腾讯云代金券