简体   繁体   中英

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. But the code section is not going into the if block.

Also I want to increment the value of the second item of the tuple of the list hr Please provide suggestions.

Edit:

list2 is a list of the form ['09', '14', '16']

And hr is the list of tuples as can be seen from the code hr.append((list2[0], 1))

hr is of the form [('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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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