list - Python,FOR 循环 - 创建列表
问题描述
这是我创建列表的代码,但它是如此残酷和不优雅,你们有什么想法让它更流畅吗?
问题是,我想编写代码,您可以在其中创建自己的列表,选择要创建的列表数量以及每个项目应该有多少项目 - 不使用 while 循环。我可以通过在 for 循环 (number_of_lists) 中输入范围来管理创建一定数量的列表
i = 0
number_of_lists = input('How many lists you want to make? >')
for cycle in range(number_of_lists): #this was originaly range(3),
item1 = raw_input('1. item > ') #and will only work now pro-
item2 = raw_input('2. item > ') #perly, if n_o_l is exact. 3
item3 = raw_input('3. item > ')
#everything is wrong with this
print "-------------------" #code, i need it much more au-
#tonomous, than it is now.
if i == 0:
list1 = [item1, item2, item3]
if i == 1:
list2 = [item1, item2, item3]
if i == 2:
list3 = [item1, item2, item3]
i += 1
print list1
print list2
print list3
事情是我也想避免所有“如果我 == int”的事情。
现在它只会创建 3 个列表,对,因为我最初使用整数 3 而不是 number_of_lists 来创建 3 个列表。
现在你看到了我希望的问题。如果可能,我需要从输入创建新列表并命名它们,因此我可以将它命名为 DOGS 或 w/e 而不是 list1。
我需要它更简单和相互关联,我希望你理解我的问题,也许有一些顺利的解决方案,谢谢:)
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 好的,我想我现在明白了 - 这是新版本,几乎可以做我想做的事情:
number_of_lists = input('How many lists you want to make? >')
allItems = []
for cycle in range(int(number_of_lists)):
items = []
number_of_items = input('How much items in this list? >')
for i in range(int(number_of_items)):
item = raw_input(str(i+1) + ". item > ")
items.append(item)
allItems.append(items)
print("-------------------")
print allItems
如果有人知道如何使它更有效和更清晰,请在这里告诉我!:) 感谢您的帮助
解决方案
您可以将您的列表添加到另一个列表中,这样它就像您想要的那样动态。下面的例子:
number_of_lists = input('How many lists you want to make? >')
allItems = []
for cycle in range(int(number_of_lists)):
items = []
for i in range(1, 4):
item = input(str(i) + ".item > ")
items.append(item)
allItems.append(items)
print("-------------------")
for items in allItems:
for item in items:
print(item)
print("-------------")
在将number_of_lists
其int
解析为int
. 如果用户输入一个字母,它会抛出一个错误。
推荐阅读
- python - 为什么这个 python 类不能与 numba jitclass 一起使用?
- python - 无法使用命令提示符执行 python 文件。给出错误“此 python 中不包含 SSL 支持”
- javascript - 在轮询发生之前状态不会更新
- powershell - 检查是否在多台服务器上安装了 Windows 安全补丁
- snakemake - 是否可以通过 Python Snakemake 中的函数返回规则?
- flutter - 如何在 Flutter 中实现 Apple 应用内订阅
- python - 将行列表转换为 Pandas 中的频率表
- java - 如何在java中修复循环while/try catch错误
- c# - c# HttpClient 似乎是删除而不是随机发布
- android - Android Kotlin 处理 EditText 更改事件