【问题标题】:Python accessing a list by namePython 按名称访问列表
【发布时间】:2015-01-21 09:00:16
【问题描述】:

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

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

【问题讨论】:

标签: python list variables eval


【解决方案1】:
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])

【讨论】:

    【解决方案2】:

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

    photos = [] # photos here
    videos = [] # videos here
    
    def move(type):
        for file in eval(type):
            print file
    
    move('photos')
    move('videos')
    

    【讨论】:

    • 一般来说,eval 永远不是正确答案
    • 但是 Gerard 正在传递字符串,所以这不是对与错的问题。这是偏好。
    • 我认为这始终是对或错的问题......但也就是说......理论上他提供的字符串来自可信来源,因此它可能 不要太可怕
    • 我会说 eval 将是解决方案。在其他语言中(我会说这是 perl 或 javascript?)我可以直接评估名称而无需使用函数 eval(这似乎总是很危险或效率低下)。如果在python中这是这样做的,我会尝试重新编写代码以避免它
    • 嗯,我完全同意。我会改为传递变量,但正如他们所说的'The customer always comes first.'
    【解决方案3】:

    好像你可以只使用字典?

    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')
    

    或者更好的是,只需将“whatever”传递给函数?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-26
      • 1970-01-01
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多