[英]How to append an integer to a string element in a nested list in Python
我有一個嵌套的字符串列表,我想為每個字符串添加一個 integer(我以后可以用作計數器)。 現在它看起來像,
words_num = [list(np.append(words[i], int(0))) for i in range(len(words))]
打印(words_num)
[['AA', '0'], ['AB', '0'], ['BB', '0']]
即使我嘗試指定 int(0),它似乎仍然是 append 一個字符串。 因此,當我將“單詞”與其他字符串進行比較時,我無法計算出現的次數(我希望能夠計算頻率)。 我還簡化了我的單詞 output 以保持示例簡潔/保持嵌套列表簡短)。 請指教!
試試這個代碼:
words = ['AA', 'AB', 'AB']
words_num = [[w, 0] for w in words]
# output: [['AA', 0], ['AB', 0], ['BB', 0]]
但是,如果我理解正確,要解決您的主要問題,這對您來說可能就足夠了:
from collections import Counter
words = ['AA', 'AB', 'BB', 'AA']
counts = Counter(words)
# output: Counter({'AA': 2, 'AB': 1, 'BB': 1})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.