[英]Making a list of lists with variable size
I'm writing a program that will accept up to five numbers and find if they're prime or not.我正在编写一个程序,最多可以接受五个数字并确定它们是否为质数。 If a number is not prime it will find their prime factors.
如果一个数不是质数,它会找到它们的质因数。 Then it will calculate the LCM of the initial numbers.
然后它将计算初始数字的 LCM。 The code I've written so far is this:
到目前为止我写的代码是这样的:
def prime(n):
if n > 1:
for i in range (2,n):
if n % i == 0:
return False
return True
def length(n):
if len(n) > 5:
return True
return False
toggle = False
enter_numbers = True
zero_one_neg = True
square = False
prime_list = [ [] for i in range(100) ]
lcm_list = [ [] for i in range(100)]
while enter_numbers:
nums = list(map(int, input('\nEnter up to five natural numbers greater than 1 separated by commas. Enter at least two if you want to calculate their LCM: ').split(',')))
for i in range (len(nums)):
if nums[i] <= 1:
zero_one_neg = True
print('\nNo zeroes, ones or negatives. Start over. ')
if length(nums) and zero_one_neg:
print('\nNo more than five numberes. Start over. ')
break
break
else:
zero_one_neg = False
if length(nums) and not zero_one_neg:
print('\nNo more than five numbers. Start over. ')
elif not length(nums) and not zero_one_neg:
enter_numbers = False
for i in range (len(nums)):
for j in range (2,nums[i]):
if nums[i] % j == 0:
lcm_list[i].append(j)
if prime(j):
prime_list[i].append(j)
toggle = True
if not toggle:
print('\n', nums[i] ,'is a prime number.')
if toggle:
print('\n', nums[i] ,'is not a prime number. It\'s prime factors are: ',prime_list[i])
print(lcm_list[i])
toggle = False
print(len(prime_list))
It's not complete of course.这当然不完整。 It runs ok but I don't like the fact i have to preset the sizes of
prime_list
and lcm_list
.它运行正常,但我不喜欢我必须预设
prime_list
和lcm_list
的大小prime_list
lcm_list
。 How can I dynamically set their sizes?如何动态设置它们的大小?
Instead of initializing the lists with a certain number of empty sublists, you can initialize them as empty lists, and append a new empty sublist for each iteration:您可以将它们初始化为空列表,并为每次迭代附加一个新的空子列表,而不是使用一定数量的空子列表初始化列表:
lcm_list = []
prime_list = []
for i in range(len(nums)):
lcm_list.append([])
prime_list.append([])
for j in range(2, nums[i]):
...
When you append you just have to have the values in square brackets to add a list into your list当您追加时,您只需将值放在方括号中即可将列表添加到您的列表中
a = []
b = [2,3]
c = [3]
#start with an empty array
print(a)
#[]
#add additional lists with whatever, this one has 2 values
a.append(b)
print(a)
#[[2, 3]]
#this just pushes the one
a.append(c)
print(a)
#[[2, 3], [3]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.