Python - 保存到列表时丢失变量实例
Python - Losing instances of variable when saving into list
我有一个函数,当我使用 list.append
时似乎正在保存变量。当我打印每个增量时,列表会发生变化。当我打印列表的完整列表时,每个元素都是相同的(变量列表的最后一个实例)。如何强制主列表保存以前的实例?
base 函数只是将列表从 base-10 转换为新的 base(在我的示例中为 base-4)
list1 = ["v", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"]
def combo(object_list, spots):
pool = len(object_list)
total = pool**spots
permlist = list()
wordlist = list()
z = []
for i in range(total):
print("top", wordlist)
wordlist.clear()
z = base(i,pool,spots)
for q in z:
j=-1
for a in object_list:
j+=1
if int(q) == int(j):
wordlist.append(a)
permlist.append(wordlist)
return permlist
def base(number, base, digits):
remainder = []
result = [0,0]
while number >0:
dividend = number // int(base)
remainder.append(str(number % int(base)))
number = dividend
result = list(reversed(remainder))
while len(result) < digits:
result.insert(0,0)
return result
print (combo(list1,4))
或者,
wordlist = []
而不是
wordlist.clear()
我有一个函数,当我使用 list.append
时似乎正在保存变量。当我打印每个增量时,列表会发生变化。当我打印列表的完整列表时,每个元素都是相同的(变量列表的最后一个实例)。如何强制主列表保存以前的实例?
base 函数只是将列表从 base-10 转换为新的 base(在我的示例中为 base-4)
list1 = ["v", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"]
def combo(object_list, spots):
pool = len(object_list)
total = pool**spots
permlist = list()
wordlist = list()
z = []
for i in range(total):
print("top", wordlist)
wordlist.clear()
z = base(i,pool,spots)
for q in z:
j=-1
for a in object_list:
j+=1
if int(q) == int(j):
wordlist.append(a)
permlist.append(wordlist)
return permlist
def base(number, base, digits):
remainder = []
result = [0,0]
while number >0:
dividend = number // int(base)
remainder.append(str(number % int(base)))
number = dividend
result = list(reversed(remainder))
while len(result) < digits:
result.insert(0,0)
return result
print (combo(list1,4))
或者,
wordlist = []
而不是
wordlist.clear()