在 Python 中使用循环创建列表
Create lists using loops in Python
我一直在研究网页抓取工具,我想创建包含不同元素的单独列表。必须有超过 1000 个列表,我正在尝试通过 for 循环运行。我需要根据每个特定迭代中的元素适当地命名列表。我尝试使用 globals() 来实现这一点,但它只需要一个 int 或一个 char 而不是一个字符串。
有办法实现吗?
举个例子:
如果people = ['John', 'James', 'Jane']
我需要 3 个列表
Johnlist=[]
Jameslist=[]
Janelist=[]
以下是我尝试过的方法,但它 returns 请求 int 或 char 时出现错误。
for p in people:
names = #scrapedcontent
globals()['%list' % p] = []
for n in names:
globals()['%list' % p].append(#scrapedcontent)
试着用字典来做:
例如:
d = {}
for p in people:
d[p] = []
names = ...
d[p].extend(names)
我强烈建议您使用 globals
、locals
或 vars
正如@roganjosh 所建议的,更喜欢使用 dict:
from collections import defaultdict
people = defaultdict(list):
for p in people:
for n in names:
people[p].append(n)
或
people = {}
for p in people:
names = #scrapedcontent
people[p] = names
不要使用这个
for p in people:
names = [] #scrapedcontent
globals().setdefault(f'list_{p}', []).extend(names)
输出:
>>> list_John
[]
>>> list_James
[]
>>> list_Jane
[]
我一直在研究网页抓取工具,我想创建包含不同元素的单独列表。必须有超过 1000 个列表,我正在尝试通过 for 循环运行。我需要根据每个特定迭代中的元素适当地命名列表。我尝试使用 globals() 来实现这一点,但它只需要一个 int 或一个 char 而不是一个字符串。 有办法实现吗?
举个例子:
如果people = ['John', 'James', 'Jane']
我需要 3 个列表
Johnlist=[]
Jameslist=[]
Janelist=[]
以下是我尝试过的方法,但它 returns 请求 int 或 char 时出现错误。
for p in people:
names = #scrapedcontent
globals()['%list' % p] = []
for n in names:
globals()['%list' % p].append(#scrapedcontent)
试着用字典来做:
例如:
d = {}
for p in people:
d[p] = []
names = ...
d[p].extend(names)
我强烈建议您使用 globals
、locals
或 vars
正如@roganjosh 所建议的,更喜欢使用 dict:
from collections import defaultdict
people = defaultdict(list):
for p in people:
for n in names:
people[p].append(n)
或
people = {}
for p in people:
names = #scrapedcontent
people[p] = names
不要使用这个
for p in people:
names = [] #scrapedcontent
globals().setdefault(f'list_{p}', []).extend(names)
输出:
>>> list_John
[]
>>> list_James
[]
>>> list_Jane
[]