如何将整数附加到 Python 中嵌套列表中的字符串元素
How to append an integer to a string element in a nested list in Python
我有一个嵌套的字符串列表,我想为每个字符串添加一个整数(我以后可以将其用作计数器)。现在它看起来像,
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),它似乎仍然附加了一个字符串。因此,当我将 "words" 与其他字符串进行比较时,我无法计算我看到的出现次数(我希望能够计算频率)。我还简化了我的单词输出以保持示例 concise/to 保持嵌套列表简短)。请指教!
试试这个代码:
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})
我有一个嵌套的字符串列表,我想为每个字符串添加一个整数(我以后可以将其用作计数器)。现在它看起来像,
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),它似乎仍然附加了一个字符串。因此,当我将 "words" 与其他字符串进行比较时,我无法计算我看到的出现次数(我希望能够计算频率)。我还简化了我的单词输出以保持示例 concise/to 保持嵌套列表简短)。请指教!
试试这个代码:
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})