Python按名称访问列表

时间:2015-01-20 22:32:10

标签: python list variables eval

我有一个定义两个列表的函数,我想基于作为参数传递的变量来引用其中一个列表。请注意,我无法将列表作为参数传递,因为列表尚不存在。

在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:
        ...

3 个答案:

答案 0 :(得分: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])

答案 1 :(得分:0)

您正在尝试传递字符串而不是变量,因此请使用eval

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

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

move('photos')
move('videos')

答案 2 :(得分: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)