python - 如何清空单独列表中列表列表中的所有项目
问题描述
我是 Python 和一般编程的新手,所以也许有一种简单的方法可以轻松做到这一点。到目前为止我写的代码是这样的(我给你所有的上下文代码):
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
def list_filter(lista):
return [x for x in lista if x]
toggle = False
enter_numbers = True
zero_one_neg = True
prime_list = []
lcm_list = []
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 numbers. 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)):
lcm_list.append([])
prime_list.append([])
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])
toggle = False
filtered_lcm_list = list_filter(lcm_list)
filtered_prime_list = list_filter(prime_list)
for i in range(len(filtered_lcm_list)):
l = list(map(int, filtered_lcm_list[i]))
print(l)
print(filtered_lcm_list)
问题出在本节:
for i in range(len(filtered_lcm_list)):
full_list = list(map(int, filtered_lcm_list[i]))
print(full_list)
print(filtered_lcm_list)
如果我输入 88,77 我得到这个输出:
Enter up to five natural numbers greater than 1 separated by commas. Enter at least two if you want to calculate their LCM: 88,77
88 is not a prime number. It's prime factors are: [2, 11]
77 is not a prime number. It's prime factors are: [7, 11]
[7, 11]
[[2, 4, 8, 11, 22, 44], [7, 11]]
Process finished with exit code 0
我想full_list
包含所有元素,filtered_lcm_list
但不包含列表列表。
解决方案
这个怎么样?
full_list = [int(i) for sub_list in filtered_lcm_list for i in sub_list]
这利用了列表推导,首先遍历包含在 中的列表filtered_lcm_list
,然后遍历每个嵌套列表中的元素。
如果您不希望返回重复的数字,您可以使用集合理解:
full_list = {int(i) for sub_list in filtered_lcm_list for i in sub_list]}
并将其转换回列表,list(full_list)
如果你愿意的话。
推荐阅读
- php - 抓取外部 json 存储到数据库中
- swift4 - iOS HealthKit - 如何获得绝对最新的当前心率,例如手表心率并发症?
- go - 动态设置结构的键和值
- php - php循环运行命令
- c# - 抛出异常:Microsoft.Azure.Devices.Client.dll 中的“System.MissingMethodException”
- javascript - 为什么通知 API 不适用于 chrome for android?
- html - CSS Web Safe Font 中的字母间距错误
- spring - Spring Batch Stream 重启问题?
- nginx - 如何卸载从其源代码安装的 Nginx?
- linux-kernel - LinuxBoot 在固件阶段与 Coreboot 有何不同?