[英]Create lists using loops in Python
I've been working on a webpage scraper and I would like to create separate lists containing different elements.我一直在研究网页抓取工具,我想创建包含不同元素的单独列表。 There would have to be more than a 1000 lists and I am trying to run that through a for loop.必须有超过 1000 个列表,我正在尝试通过 for 循环运行它。 I need the lists to be appropriately named according to the element in each particular iteration.我需要根据每个特定迭代中的元素适当地命名列表。 I tried using globals() to achieve this but it only takes an int or a char and not a string.我尝试使用 globals() 来实现这一点,但它只需要一个 int 或一个 char 而不是一个字符串。 Is there a way to achieve this?有没有办法做到这一点?
For an example: If people = ['John', 'James', 'Jane']
I need 3 lists named Johnlist=[]
Jameslist=[]
Janelist=[]
例如:如果people = ['John', 'James', 'Jane']
我需要 3 个名为Johnlist=[]
Jameslist=[]
Janelist=[]
的列表
Below is what I tried but it returns an error asking for either an int or a char.以下是我尝试过的,但它返回一个错误,要求输入 int 或 char。
for p in people:
names = #scrapedcontent
globals()['%list' % p] = []
for n in names:
globals()['%list' % p].append(#scrapedcontent)
I strongly discourages you to use globals
, locals
or vars
As suggested by @roganjosh, prefer to use dict:我强烈不鼓励您使用globals
, locals
或vars
正如@roganjosh 所建议的,更喜欢使用 dict:
from collections import defaultdict
people = defaultdict(list):
for p in people:
for n in names:
people[p].append(n)
Or或者
people = {}
for p in people:
names = #scrapedcontent
people[p] = names
try to do it in a dict:尝试在字典中执行此操作:
for example:例如:
d = {}
for p in people:
d[p] = []
names = ...
d[p].extend(names)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.