简体   繁体   English

在元组列表中查找字符串

[英]Find string in a List of Tuples

I am appending a tuple to the list if I don't find the string. 如果找不到该字符串,我会将元组追加到列表中。

if list2[0] in hr:
    print "X"
else:
    hr.append((list2[0], 1))

print "X" is arbitary. print "X"是任意的。 But the code section is not going into the if block. 但是代码部分没有进入if块。

Also I want to increment the value of the second item of the tuple of the list hr Please provide suggestions. 我也想增加列表hr的元组第二项的值。请提供建议。

Edit: 编辑:

list2 is a list of the form ['09', '14', '16'] list2是形式为['09', '14', '16']

And hr is the list of tuples as can be seen from the code hr.append((list2[0], 1)) hr是元组列表,可以从代码hr.append((list2[0], 1))看到

hr is of the form [('09', 1), ('18', 1)] hr的格式为[('09', 1), ('18', 1)]

Also the increment is to change [('09', 1), ('18', 1)] to [('09', 1), ('18', 2)] when encounter '18' again in list2 All the operations are being carried out inside a loop reading a file. 同样[('09', 1), ('18', 2)]当在list2再次遇到'18'时,增量将[('09', 1), ('18', 1)]更改为[('09', 1), ('18', 2)]这些操作是在读取文件的循环内执行的。

Try this: 尝试这个:

item_found = False
for index, item in enumerate(hr):
    if list2[0] == item[0]:
        item_found = True #found the item
        hr[index] = (item[0], item[1]+1) #increment by 1
        break #don't loop more than we need to
if not item_found:
    hr.append((list2[0], 1)) #add new item

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM