假設我想使用forloop自動生成大標題行的索引,以防止爲每個標題寫索引。如何使用for-loop使用列表元素的值自動生成變量?
在一個文件中,我說了一個包含很多水果名稱的標題。每列都有一個數據,我必須使用索引訪問下游解析。我不想爲每個水果名稱準備索引,而是希望運行forloop以實時創建索引值以節省時間。
data =
apple banana orange
genus:x,species:b genus:x,species:b genus:x,species:b
genus:x,species:b genus:x,species:b genus:x,species:b
variety:gala,pinklady,... variety:wild,hybrid... variety:florida,venz,
flavors:tangy,tart,sweet..
global_consumption:....
pricePerUnit:...
seedstocks:.....
insect_resistance:.....
producer:....
# first I convert the header into list like this:
for lines in data:
if 'apple' in lines:
fruits = lines.split('\t')
# this will give me header as list:
# ['apple', 'banana', 'orange']
# then create the index as:
for x in fruits:
str(x) + '_idx' = fruits.index(x)
# this is where the problem is for me .. !??
# .. because this is not valid python method
print(x)
# if made possible, new variable are created as
apple_idx = 0, banana_idx = 1 ... so on
# Now, start mining your data for interested fruits
data = lines.split('\t')
apple_values = data[apple_idx]
for values in apple_values:
do something ......
same for others. I also need to do several other things.
Make sense??
這怎麼能成爲可能?以一種非常簡單的方式。
帖子編輯:做大量的閱讀後,我意識到,這是可能的在bash創建使用其他varible的value(string)
一個variable_name
:
how to use a variable's value as other variable's name in bash
但是,在我看來,python是不可能的。我的直覺是,可以在python編程語言中編寫這種方法(如果被黑客攻擊或作者決定),但python的作者也有可能想到並瞭解可能的危險或使用這種方法。
- 危險之處在於您總是希望
variable_name
在寫入的python腳本中可見。準備一個動態variable_names本來不錯,但如果出現任何問題,它可能會導致回溯時出現問題。 - 因爲變量名從來沒有輸入過,如果出現任何問題(特別是在大型程序中),比如說變量值類似於
2BetaTheta
或*ping^pong
這不是有效的變量名稱,那將是一個噩夢來跟蹤和調試。我的想法。 請其他人可以在爲什麼這個功能沒有被引入python? - 字典方法結束了這個問題,因爲我們有
variable_name
的起源記錄,但仍然有效與無效variable_name的問題不會消失。
我打算採用dict method
提供的答案,看看我能否找到一個非常簡單而全面的方法來實現這一點。
謝謝大家!
這是一個[XY問題](http://mywiki.wooledge.org/XyProblem) - 意思是說,你問的是你認爲是你想解決的問題的一個很好的解決方案,而不是詢問你試圖解決的實際問題。沒有理由用您嘗試的方式命名具有不同名稱的變量。你想要實現的是什麼? –
我想在variablename是(x-name +'_idx')時自動創建一個變量,它的值是它在該列表中的位置。 – everestial007
也許你可以創建一本詞典?然後你可以像dict [「apple」]那樣訪問它,並且你可以得到相應的索引。 – Antimony