【问题标题】:Appending int value to a bunch of list variables将 int 值附加到一堆列表变量
【发布时间】:2021-04-03 05:19:56
【问题描述】:
我正在尝试一次将一个 int 值附加到一堆列表变量中。是否有一个 for 循环或这样的函数可以让我这样做?就像我想将 val int 附加到下面定义的所有列表变量中。
val = 100
list_1=[]
list_2=[]
list_3=[]
list_4= []
【问题讨论】:
标签:
python
python-3.x
list
for-loop
append
【解决方案1】:
对于这样的事情,我更喜欢一个函数来这样做,因为你很可能会再次这样做。
def appendAll(value, *args):
for listItem in args:
listItem.append(value)
这允许您向任何列表集添加值。它不需要您设置变量列表,因为 *args 允许您传递任意数量的参数并创建一个元组,让我们可以遍历每个列表并将我们的值附加到每个列表。
list1 = []
list2 = []
list3 = []
val = []
#now we can append val to all the lists or some of them
appendAll(val, list1, list2, list3)
【解决方案2】:
创建一个包含所有列表的列表,然后使用循环:
val = 100
list_1 = []
list_2 = []
list_3 = []
list_4 = []
list_of_lists = [list_1, list_2, list_3, list_4]
for li in list_of_lists:
li.append(val)
警告:不要不要试图通过以下方式创建list_of_lists:
list_of_lists = [[]] * 4
这将创建一个包含 4 个引用的单个列表,并且通过其中 1 个所做的更改将被所有其他人看到。
但是,您可以做到
list_of_lists = [[] for _ in range(4)]
for li in list_of_lists:
li.append(100)
print(list_of_lists)
# [[100], [100], [100], [100]]