Python中如何获取列表元素对应的原始变量名?
如何获取列表元素对应的变量名
你当前的Movies列表中存储的是各个电影列表的实际值,而非变量名,因此直接索引只能拿到值。要获取原来的变量名,需要主动将名称与内容关联存储,以下是两种常用实现方式:
方法1:使用字典存储映射关系
字典可以直接将电影名称(原变量名)作为键,对应的内容列表作为值,方便快速获取名称和内容:
# 保留原有的电影内容定义 TheShawshankRedemption = ['drama' , 1994, 'Frank Darabont', 'Tim Robbins', 'Morgan Freeman', 'Bob Gunton', 'Stephen King'] TheGodfather = ['crime', 'drama', 'Francis Ford Coppola', 1972, 'Mario Puzo', 'Marlon Brando','Al Pacino', 'James Caan'] TheDarkKnight = ['action', 'crime', 'drama', 2008, 'Christopher Nolan', 'Jonathan Nolan', 'David S. Goyer', 'Christian Bale', 'Heath Ledger', 'Aaron Eckhart'] SchindlersList = ['biography', 'drama', 'history', 1993, 'Steven Spielberg', 'Liam Neeson',' Ralph Fiennes',' Ben Kingsley'] TheLordoftheRingsTheReturnoftheKing= ['action', 'adventure', 'drama', 2003, 'Peter Jackson', 'J.R.R. Tolkien', 'Elijah Wood', 'Viggo Mortensen', 'Ian McKellen'] PulpFiction = ['crime', 'drama', 1994, 'Quentin Tarantino', 'John Travolta', 'Uma Thurman', 'Samuel L. Jackson'] FightClub = ['drama', 1999, 'David Fincher', 'Brad Pitt', 'Edward Norton', 'Meat Loaf'] # 用字典关联名称和内容 Movies = { 'TheShawshankRedemption': TheShawshankRedemption, 'TheGodfather': TheGodfather, 'TheDarkKnight': TheDarkKnight, 'SchindlersList': SchindlersList, 'TheLordoftheRingsTheReturnoftheKing': TheLordoftheRingsTheReturnoftheKing, 'PulpFiction': PulpFiction, 'FightClub': FightClub } # 获取第一个电影的名称 first_movie_name = list(Movies.keys())[0] print(first_movie_name) # 输出:TheShawshankRedemption # 同时获取名称和对应内容 print(f"{first_movie_name}: {Movies[first_movie_name]}")
方法2:使用元组列表存储名称与内容对
如果需要保持顺序,可以用元组列表,每个元组包含名称和对应的内容:
# 保留原有的电影内容定义 TheShawshankRedemption = ['drama' , 1994, 'Frank Darabont', 'Tim Robbins', 'Morgan Freeman', 'Bob Gunton', 'Stephen King'] # ... 其他电影变量定义不变 # 构建元组列表,每个元素是(名称, 内容) Movies = [ ('TheShawshankRedemption', TheShawshankRedemption), ('TheGodfather', TheGodfather), ('TheDarkKnight', TheDarkKnight), ('SchindlersList', SchindlersList), ('TheLordoftheRingsTheReturnoftheKing', TheLordoftheRingsTheReturnoftheKing), ('PulpFiction', PulpFiction), ('FightClub', FightClub) ] # 获取第一个电影的名称 print(Movies[0][0]) # 输出:TheShawshankRedemption # 获取第一个电影的内容 print(Movies[0][1])
补充说明
Python中变量名只是对内存中对象的引用,列表中存储的是对象本身,无法直接通过对象反向获取它原来的变量名。必须通过上述方式主动建立名称与对象的关联,才能实现需求。
内容的提问来源于stack exchange,提问作者Yiğit Yılmaz
相关产品推荐
相关产品推荐

