简体   繁体   中英

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. 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. Is there a way to achieve this?

For an example: If people = ['John', 'James', 'Jane'] I need 3 lists named Johnlist=[] Jameslist=[] Janelist=[]

Below is what I tried but it returns an error asking for either an int or a 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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM