简体   繁体   English

在python或空数组中创建多个列表

[英]Creating multiple lists in python or empty arrays

Hello I'm Just searching for a way to create multiple lists at once. 您好,我只是在寻找一次创建多个列表的方法。 by that I mean. 我的意思是

day1 = []
day2 = []
up to 7 days....
day7 = []

instead of having to copy and paste all the time and make my code look unprofessional and not looking good. 而不是一直复制和粘贴,并使我的代码看起来不专业并且看起来也不好。 I wanted to create a loop that creates these lists automatically. 我想创建一个自动创建这些列表的循环。

Here are a couple of options: 这里有几个选择:

1. A basic list comprehension: 1.基本的清单理解:

seven_lists = [[] for i in range(7)]

Which gives a nested list of seven lists: 给出了七个列表的嵌套列表:

[[], [], [], [], [], [], []]

2. A list of (day, []) tuples: 2. (day, [])元组的列表:

days = [("day " + str(i+1), []) for i in range(7)]

Which gives: 这使:

[('day 1', []), ('day 2', []), ('day 3', []), ('day 4', []), ('day 5', []), ('day 6', []), ('day 7', [])]

3. A dictionary of days: 3.天字典:

days = {"day " + str(i+1) : [] for i in range(7)}

Which gives: 这使:

{'day 1': [], 'day 2': [], 'day 3': [], 'day 4': [], 'day 5': [], 'day 6': [], 'day 7': []}

And then you can access/update each/multiple days like this: 然后,您可以像这样访问/更新每/多天:

>>> days['day 1']
[]
>>> days['day 1'].append(1)
>>> days['day 1']
[1]
>>> days
{'day 1': [1], 'day 2': [], 'day 3': [], 'day 4': [], 'day 5': [], 'day 6': [], 'day 7': []}
>>> days.update({'day 2': [1, 2, 3]})
>>> days
{'day 1': [1], 'day 2': [1, 2, 3], 'day 3': [], 'day 4': [], 'day 5': [], 'day 6': [], 'day 7': []}

you can use dict 你可以用字典

dct = {}
for i in range(1,8):
   dct["day"+str(i)] = []

or dict comprehensions 或dict理解

dct = { 'day'+str(i):[] for i in range(1,8) }

output: 输出:

{'day6': [], 'day7': [], 'day4': [], 'day5': [], 'day2': [], 'day3': [], 'day1': []}

我能想到的最短的方法就是这个。

day1, day2, day3, day4, day5, day6, day7 = [], [], [], [], [], [], []

An odd way that is sometimes worthwhile is 有时值得的奇怪方法是

from collections import defaultdict
days = defaultdict(list)
print(days['day1']) #prints [], 

Doing this you can use whatever you like for day of week keys as long as you are consistent. 这样做的话,只要您保持一致,就可以将任意时间用于星期几键。 Like 喜欢

days['Monday']

or use number keys to make it look like an array. 或使用数字键使其看起来像数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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