如何在列表列表中强制单独处理相同的元素?
How to force process identical elements individually in a list of lists?
我正在编写一个标记词性的程序,生成一个列表列表。这是程序中的示例函数:
phrase = [['he',''],['is', ''],['believed', ''],['to',''],['have',''],['believed','']]
def parts_tagger(input_list):
parts = []
for [x,y] in input_list:
prior_word = input_list[input_list.index([x,y]) - 1][0]
if x.startswith('be') and y == '' and prior_word == 'is':
parts.append([x,'passive'])
else:
parts.append([x,y])
return parts
print (parts_tagger(phrase))
当您 运行 这段代码时,Python 找到条件适用的第一个单词(第一个 "believed")并正确标记它:
[['he', ''], ['is', ''], ['believed', 'passive'], ['to', ''], ['have', ''], ['believed', 'passive']]
但随后它以某种方式将相同的标签应用于列表中条件不适用的其他相同单词(第二个 "believed")。我究竟做错了什么?如何解决这个问题并强制 Python 单独处理列表中的每个项目?
问题出在这一行
prior_word = input_list[input_list.index([x,y]) - 1][0]
list.index
returns 第一个匹配项的索引。
Return the index in the list of the first item whose value is x. It is an error if there is no such item.
您可以使用enumerate
来解决您的问题。将循环和下一行更改为这些。
for ind,[x,y] in enumerate(input_list):
prior_word = input_list[ind - 1][0]
输出将符合预期
[['he', ''], ['is', ''], ['believed', 'passive'], ['to', ''], ['have', ''], ['believed', '']]
与 Shawn pointed out below (in a now deleted comment) 一样,我认为您需要从第二个索引开始,然后自己手动填充第一个元素的值。这是因为对于第一个元素,您将没有任何先前的值。这个
有两个 work-around(s)
从第二个元素开始
for ind,[x,y] in enumerate(input_list[1:],start=1):
在您的 body 中添加一个条件。
for ind,[x,y] in enumerate(input_list):
prior_index = ind - 1
if prior_index<0:
# Do something
break
prior_word = input_list[ind - 1][0]
我正在编写一个标记词性的程序,生成一个列表列表。这是程序中的示例函数:
phrase = [['he',''],['is', ''],['believed', ''],['to',''],['have',''],['believed','']]
def parts_tagger(input_list):
parts = []
for [x,y] in input_list:
prior_word = input_list[input_list.index([x,y]) - 1][0]
if x.startswith('be') and y == '' and prior_word == 'is':
parts.append([x,'passive'])
else:
parts.append([x,y])
return parts
print (parts_tagger(phrase))
当您 运行 这段代码时,Python 找到条件适用的第一个单词(第一个 "believed")并正确标记它:
[['he', ''], ['is', ''], ['believed', 'passive'], ['to', ''], ['have', ''], ['believed', 'passive']]
但随后它以某种方式将相同的标签应用于列表中条件不适用的其他相同单词(第二个 "believed")。我究竟做错了什么?如何解决这个问题并强制 Python 单独处理列表中的每个项目?
问题出在这一行
prior_word = input_list[input_list.index([x,y]) - 1][0]
list.index
returns 第一个匹配项的索引。
Return the index in the list of the first item whose value is x. It is an error if there is no such item.
您可以使用enumerate
来解决您的问题。将循环和下一行更改为这些。
for ind,[x,y] in enumerate(input_list):
prior_word = input_list[ind - 1][0]
输出将符合预期
[['he', ''], ['is', ''], ['believed', 'passive'], ['to', ''], ['have', ''], ['believed', '']]
与 Shawn pointed out below (in a now deleted comment) 一样,我认为您需要从第二个索引开始,然后自己手动填充第一个元素的值。这是因为对于第一个元素,您将没有任何先前的值。这个
有两个 work-around(s)从第二个元素开始
for ind,[x,y] in enumerate(input_list[1:],start=1):
在您的 body 中添加一个条件。
for ind,[x,y] in enumerate(input_list): prior_index = ind - 1 if prior_index<0: # Do something break prior_word = input_list[ind - 1][0]