在Python3中将变量名转换为字符串

2024-04-20 08:40:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表列表,我想将其转换为字符串列表,其中字符串是变量的名称。我想循环查看列表并将列表的长度提取到一个列表中,将列表的名称提取到另一个列表中。为了说明这一点,我们尝试使用str(variable)来实现这一点,这显然行不通,因为它转换的是变量的值,而不是名称。我想把名字改过来

# Here are the initial lists
common_nouns = ['noun', 'fact', 'banana']
verbs = ['run', 'jump']
adjectives = ['red', 'blue']
# Here is my list of lists:
parts_of_speech = [common_nouns, verbs, adjectives]
labels=[]
data=[]
for pos in parts_of_speech:
    if pos != []:
        labels.append(str(pos)) # This part doesn't work
        data.append(len(pos))

结果:

^{pr2}$

期望结果:

labels = ['common_nouns', 'verbs', 'adjectives']

编辑:添加初始列表


Tags: of字符串pos名称列表labelsherecommon
2条回答

这与如何拥有“可变变量”的常见问题相反。但答案是一样的:不要那样做,用口述

将这些数据存储为单个dict,并将这些值作为键,然后可以使用.keys()方法来获得所需的结果。在

最后我按照丹尼尔·罗斯曼的建议编了一本词典。实现如下:

parts_of_speech = [common_nouns, verbs, adjectives]
all_labels = ['common_nouns', 'verbs', 'adjectives']
pos_dict = dict(zip(all_labels, parts_of_speech))
labels=[]
data=[]
for pos, lst in pos_dict.items():
    if lst:
        data.append(len(lst))
        labels.append(pos)

相关问题 更多 >