0

I have a nested list of strings and I'd like to add an integer to each string (that I can later use as a counter). Right now it looks something like,

words_num = [list(np.append(words[i], int(0))) for i in range(len(words))]

print(words_num)

[['AA', '0'], ['AB', '0'], ['BB', '0']]

Even though I try specifying int(0), it seems to still append a string. As such, I can't count the number of occurrences I see my "words" when I compare it to other strings (I'd like to be able to count frequency). I've also simplified my word output to keep the example concise/to keep the nested list short). Please advise!

2
  • 1
    Maybe there's no need to use numpy. Could you paste the words and the output you expect ? Commented Oct 4, 2019 at 4:26
  • 2
    Why not simply drop numpy and go : words_num = [[word, 0] for word in words]? Commented Oct 4, 2019 at 4:26

1 Answer 1

1

Try this code:

words = ['AA', 'AB', 'AB']
words_num = [[w, 0] for w in words]

# output: [['AA', 0], ['AB', 0], ['BB', 0]]

However, if I understand correctly, to solve your main problem, this is probably enough for you:

from collections import Counter
words = ['AA', 'AB', 'BB', 'AA']
counts = Counter(words)

# output: Counter({'AA': 2, 'AB': 1, 'BB': 1})
Sign up to request clarification or add additional context in comments.

2 Comments

Everyone is correct, turns out I do not need numpy! The above code worked - thank you!!
I updated the answer, if I understood your problem, you could solve everything as I wrote above

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.