简体   繁体   中英

Find a matching string and then + 1 to element

I'm trying to make a loop to go through a 2 dimensional list, if the loop finds the matching string that is in the first element then it adds +1 to the second element of the list.

An example of the list:

[[mike, 0], [john, 2], [henry, 0], [sam, 1]]

If the required search was for John this would happen:

[[mike, 0], [john, 3], [henry, 0], [sam, 1]]

And then for Mike:

[[mike, 1], [john, 3], [henry, 0], [sam, 1]]

In the below scenario 'name' is the string getting brought in that needs to be found.

I'm also pulling the list of names in from a CSV file and then writing the updated list back.

I can't seem to get this to work, and the error that is coming back to me is

'TypeError: int() argument must be a string, a bytes-like object or a number, not 'list''

def count(name):
    with open('nameList.csv', 'r') as csvfile:
        reader = csv.reader(csvfile)
        nameList = list(reader)
    for x in range(len(nameList)):
        if nameList[x][0] == name:
            print(nameList== name)
            nameList[1] = nameList[1] + 1
    with open("nameList.csv", "w", newline='') as f:
        writer = csv.writer(f)
        for i in nameList:
            writer.writerow(i)

Any ideas about how to get this working? Much appreciated!


I believe that the original problem you are trying to solve is to get the counts of the names.

If that's the case, then it can be accomplished much more easily using Counter from Python's collections module.

from collections import Counter

cnt = Counter()
with open("nameList.csv", 'r') as f:
    rd = csv.reader(f)
    cnt = Counter(r[0] for r in rd)

print(cnt)


cnt will be dict-like object (you can use it just like any other dictionary) where the keys are the names from the CSV and the values are the counts. So, it might look something like this:

{'john': 3, 'mike': 1, 'sam': 1}


Now suppose you have another CSV with names and you want to find the count of each name in both the files. You can do this just as easily, by updating cnt :

with open("nameList2.csv", 'r') as f:
    rd2 = csv.reader(f)
    cnt.update(r[0] for r in rd2)

You avoid counting from scratch and the code is way more sexy! Simple and elegant!

The one thing that stands out is this line:

 nameList[1] = nameList[1] + 1

nameList[1] is the second inner list in your main list. I think you probably meant nameList[x][1] :

nameList[x][1] = nameList[x][1] + 1

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