Python 按名称访问列表
Python accessing a list by name
我有一个定义两个列表的函数,我想根据作为参数传递的变量引用其中一个列表。请注意,我无法将列表作为参数传递,因为该列表尚不存在。
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:
...
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])
您正在尝试传递字符串而不是变量,因此请使用 eval
photos = [] # photos here
videos = [] # videos here
def move(type):
for file in eval(type):
print file
move('photos')
move('videos')
看来你只能用字典了?
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)
我有一个定义两个列表的函数,我想根据作为参数传递的变量引用其中一个列表。请注意,我无法将列表作为参数传递,因为该列表尚不存在。
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:
...
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])
您正在尝试传递字符串而不是变量,因此请使用 eval
photos = [] # photos here
videos = [] # videos here
def move(type):
for file in eval(type):
print file
move('photos')
move('videos')
看来你只能用字典了?
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)