[英]Why output returning list and str
說我有熊貓數據集中一些獨特國家的清單
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'
當我檢查country_filter [1]的類型時
In[]:type(countries_filter[1])
Out[]: str
輸出是str
但是當我從countries_filter[1]
刪除[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]
在這里扮演什么角色?
我不確定您的熊貓框架中有什么,但是如果您將代碼更改為以下內容:
random.sample(countries.head(),m)[n]
這將返回含有清單m
樣品(在你的情況1)從提供的列表countries
。 使用[n]
從列表中選擇第n個項目(從0開始)(在您的情況下為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
基本上是:第一次使用random.sample
創建新列表,而第二次調用該函數時,您只想替換該列表中的一個項目,因此在使用之前先解壓縮列表它的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.