python-3.x - 在python中创建具有不同索引的列表
问题描述
我正在尝试使用循环创建一个列表,但我希望该组具有相同的索引。使用追加,它将它们合并在一起。我究竟做错了什么?
L=[]
l=[]
def information():
i=0
while i <= 3:
if i==0:
first_name = str(input('First Name : '))
l.append(first_name)
i += 1
elif i==1:
last_name = str(input('Second Name : '))
l.append(last_name)
i += 2
elif i > 2:
wish = str(input('If you wish to continue Press Y/y or Press N/n:'))
if wish == 'y' or wish == 'Y':
L.append(l)
start()
elif wish != 'y' or wish != 'Y':
break
def start():
information()
start()
print('l', l)
print('L ', L)
我想要的输出是:
[['sachin', 'tendulkar'],['sachin', 'tendulkar'],['sachin', 'tendulkar']]
我得到了这个:
['sachin', 'tendulkar','sachin', 'tendulkar']
解决方案
与您所做的有点不同,但这可能会奏效
Names = []
def information():
wish = str(input("Do you wish to add a name? Press Y/y for yes or Press N/n for no: "))
while ((wish == 'y') or (wish == 'Y')):
fname = str(input('First Name: '))
lname = str(input('Last Name: '))
Names.append([fname, lname])
wish = str(input("Do you wish to add a name? Press Y/y for yes or Press N/n for no: "))
information()
print (Names)
推荐阅读
- r - R 函数采用数据框和列列表,然后为这些列中的每一个添加二值化变量到原始数据框
- php - 在 Symfony 中使用 OR 逻辑验证多个约束
- javascript - Electron - 为什么在关闭事件中将 BrowserWindow 实例设置为 null
- amazon-web-services - 无法在 aws (kube-aws) 中使用 jenkins 创建集群
- django - 在不影响旧迁移文件的情况下使用 Django-2 升级 wagtail-2。我得到这个“NoneType”对象没有属性“is_relation”
- oracle - ORacle基于组在同一列中维护多个序列
- macos - 未找到 Arduino 可执行文件
- reporting-services - SSRS - 总结第一张表,详细说明后面的表
- javascript - 承诺
被转换成 ZoneAwarePromise - javascript - 配置 Eclipse 以将 .sah 扩展名视为 .js 扩展名