首页 > 解决方案 > 在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']

标签: python-3.x

解决方案


与您所做的有点不同,但这可能会奏效

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)

推荐阅读