假设我有一份来自熊猫数据集的一些独特国家的名单
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]
扮演什么角色?你知道吗
我不确定,熊猫框架中有什么,但如果您将代码更改为以下内容:
它返回一个包含
m
样本的列表(在您的案例1中),这些样本来自countries
中提供的列表。使用[n]
从列表中选择从0开始的第n项(对于0,这对应于第一项)。你知道吗我举了一个例子来说明当你在你的采样例程中增加
1
时会发生什么-我想这会让你更容易理解:编辑更新的问题:
混淆可能是因为以下原因: 当您执行代码的第一部分时,例如
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
创建一个新列表时,而第二次调用函数时,您只想替换该列表中的一个项目,因此在使用列表内容之前先解压列表。你知道吗相关问题 更多 >
编程相关推荐