假设我有Pandas数据集中的一些独特国家/地区的列表
use NCurses;
my $win = initscr();
addstr( 'AAA' );
nc_refresh();
sleep 2;
delwin( $win );
endwin();
...
my $new_win = initscr();
if ! $new_win.defined {
endwin();
dd $new_win; # NCurses::WINDOW $new_win = NCurses::WINDOW
die "win undefined"; # win undefined
}
addstr( 'BBB' );
nc_refresh();
sleep 2;
delwin( $new_win );
endwin;
我随机过滤了2个国家/地区,
更新:发布了代码
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']
当我检查countries_filter [1]
的类型时In[]: countries_filter[1] = random.sample(countries,1)[0]
In[]: countries_filter[1]
Out[]: 'Japan'
输出为In[]:type(countries_filter[1])
Out[]: str
,但当我从str
[0]
时
countries_filter[1]
并检查类型输出是In[]: countries_filter[1] = random.sample(countries,1)
In[]: countries_filter[1]
Out[]: ['Japan']
In[]: type(countries_filter[1])
Out[]: list
list
在这里扮演的角色是什么?
答案 0 :(得分:0)
我不确定,您的熊猫框架中有什么,但如果您将代码更改为以下内容:
random.sample(countries.head(),m)[n]
这将从m
中提供的列表中返回包含countries
个样本(在您的案例中为1)的列表。使用[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]
)的类型为字符串。但是现在您通过执行random.sample(countries,1)[0]
将其替换为新项目。由于您只是替换列表中的一个元素,您想要的只是从random.sample
获取列表内容,因此您需要[0]
。如果您没有这样做,整体结果看起来会像这样:['Bhutan', ['Japan']]
。
因此,可能导致问题的差异基本上是:第一次使用random.sample
创建新列表,而对于第二次调用该函数,您只想替换该列表中的一个项目,因此在使用其内容之前解压缩列表。