将 int 值附加到一堆列表变量
Appending int value to a bunch of list variables
我想一次将一个 int 值附加到一堆列表变量中。是否有 for 循环或这样的函数可以让我这样做?就像我想将 val int 附加到下面定义的所有列表变量中。
val = 100
list_1=[]
list_2=[]
list_3=[]
list_4= []
创建一个包含所有列表的列表,然后使用循环:
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]]
对于这样的事情,我更喜欢一个函数来这样做,因为你很可能会再次这样做。
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)
我想一次将一个 int 值附加到一堆列表变量中。是否有 for 循环或这样的函数可以让我这样做?就像我想将 val int 附加到下面定义的所有列表变量中。
val = 100
list_1=[]
list_2=[]
list_3=[]
list_4= []
创建一个包含所有列表的列表,然后使用循环:
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]]
对于这样的事情,我更喜欢一个函数来这样做,因为你很可能会再次这样做。
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)