为什么输出返回列表和

2024-10-02 22:30:39 发布

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

假设我有一份来自熊猫数据集的一些独特国家的名单

countries.head()

['Arab World',
 'Caribbean small states',
 'Central Europe and the Baltics',
 'East Asia & Pacific (all income levels)',
 'East Asia & Pacific (developing only)',
 'Euro area']

我随机筛选了两个国家

更新:发布代码

In[]: countries_filter = random.sample(countries,2)
Out[] : ['Bhutan', 'Japan']

如果我想随机选择第二个国家,请再次选择:

In[]: countries_filter[1] = random.sample(countries,1)[0]
In[]: countries_filter[1]
Out[]: 'Japan'

当我检查过滤器[1]的类型时

In[]:type(countries_filter[1])
Out[]: str

输出是str,但是当我从countries_filter[1]中删除[0]

In[]: countries_filter[1] = random.sample(countries,1)
 In[]: countries_filter[1]
 Out[]: ['Japan']

In[]: type(countries_filter[1])
Out[]: list

并检查类型输出是否为list

在这里[0]扮演什么角色?你知道吗


Tags: samplein类型typerandom国家filterout
1条回答
网友
1楼 · 发布于 2024-10-02 22:30:39

我不确定,熊猫框架中有什么,但如果您将代码更改为以下内容:

random.sample(countries.head(),m)[n]

它返回一个包含m样本的列表(在您的案例1中),这些样本来自countries中提供的列表。使用[n]从列表中选择从0开始的第n项(对于0,这对应于第一项)。你知道吗

我举了一个例子来说明当你在你的采样例程中增加1时会发生什么-我想这会让你更容易理解:

In[]: random.seed(42)              # ensures same output for all sampling runs
In[]: random.sample(countries.head(),3)
Out[]:
['Arab World', 'Caribbean small states', 'Central Europe and the Baltics']
In[]: random.sample(countries.head(),3)[0]
Out[]:
'Arab World'
In[]: random.sample(countries.head(),3)[1]
Out[]:
'Caribbean small states'

编辑更新的问题:

混淆可能是因为以下原因: 当您执行代码的第一部分时,例如countries_filter = random.sample(countries,2),在counties_filter中将有两个项目,即len(countries_filter)将返回2。你知道吗

此时,第二项(即countries_filter[1])是string类型。但是现在您通过执行random.sample(countries,1)[0]将它替换为一个新项。由于您只是替换列表中的一个元素,所以只需要从random.sample获取列表内容,因此需要[0]。如果不这样做,总体结果会像这样:['Bhutan', ['Japan']]。你知道吗

因此,可能导致问题的区别基本上是:第一次使用random.sample创建一个新列表时,而第二次调用函数时,您只想替换该列表中的一个项目,因此在使用列表内容之前先解压列表。你知道吗

相关问题 更多 >