2015-01-20 97 views
-4

我有一個函數,它定義了兩個列表,我想參考這些列表中基於作爲參數傳遞的變量的列表之一。請注意,我無法將列表作爲參數傳遞,因爲列表尚不存在。Python按名稱訪問列表

在Python中做簡單嗎?或者我應該之外創建的列表,並將它們作爲參數傳遞爲簡單起見

def move(self,to_send): 
    photos = ['example1'] 
    videos = ['example2'] 
    for file in @to_send: #where @to_send is either 'photos' or 'movies' 
     ... 

if whatever: 
    move('photos') 
else: 
    move('videos') 

編輯: 爲了避免EVAL字符串轉換成一個列表,我可以做

def move(self,to_send): 
    photos = ['example1'] 
    videos = ['example2'] 
    if to_send == 'photos': 
     to_send = photos 
    else: 
     to_send = videos 
    for file in to_send: 
     ... 
+1

實例請,這是不清楚:)) – 2015-01-20 22:34:36

+0

以何種方式被分別定義方法'移動(自我,類型名)''做移動( '照片')''然後移動( '視頻')'一問題?很簡單,很明顯,它就像表演一樣。 – smci 2015-01-20 22:42:32

+3

順便說一下,[不要在Python中使用「type」作爲變量名](http://stackoverflow.com/questions/10568087/is-it-safe-to-use-the-python-word-type在我的代碼中),它是[內建](https://docs.python.org/2/library/functions.html#type) – smci 2015-01-20 22:43:18

回答

0

您正在試圖通過字符串,而不是變量,所以使用eval

photos = [] # photos here 
videos = [] # videos here 

def move(type): 
    for file in eval(type): 
     print file 

move('photos') 
move('videos') 
+7

作爲一般經驗法則'eval'永遠不是正確的答案 – 2015-01-20 22:39:06

+0

但傑拉德正在傳遞字符串,所以這不是一個對與錯的問題。這是偏好。 – 2015-01-20 22:41:24

+0

線程的標題是「Python按名稱訪問列表」。 – 2015-01-20 22:42:55

4
def move(self,type): 
    photos = ['example1'] 
    movies = ['example2'] 
    for file in locals()[type]: 
      ... 

move("photos") 

更好將是保持一個列表的列表

my_lists = { 
    "movies":... 
    "photos":... 
} 

variable="movies" 
do_something(my_lists[variable]) 
0

看來你可以只使用一本字典一樣?

def move(to_send): 
    d = { 
     'photos' : ['example1'] 
     'videos' : ['example2'] 
    } 
    for file in d[to_send]: #where @to_send is either 'photos' or 'movies' 
     ... 

if whatever: 
    move('photos') 
else: 
    move('videos') 

或者更好的是,只要通過「無論」功能?

def move(whatever): 
    if whatever: 
     media = ['example1'] 
    else: 
     media = ['example2'] 
    for file in media: 
     ... 
move(whatever)