简体   繁体   English

创建元组列表,将元组元素用作输入

[英]Create list of tuples , tuple elements taken as Input

I wish to create a list whose members are tuples, taken from console input. 我希望创建一个列表,其成员是元组,从控制台输入中获取。 I've seen other questions which describe about tuples and lists. 我看过其他有关元组和列表的问题。 But how to create tuples from input and append them to list till the choice to take tuple elements is no, 'n'? 但是如何从输入创建元组并将其附加到列表中,直到选择元组元素的选择为“ n”? I tried the following code. 我尝试了以下代码。

"""
Create the tuples into a list.
"""

def createTupledList() :
    l=[]
    print("Add an element for the tuple ? y/n : ")
    ch=str(input())
    while(ch=='y') :
        print("Enter the tuple element : ")
        i=input()
        l=l.append(tuple(i))
        print("Add an element for the tuple ? y/n : ")
        ch=str(input())
    return l



l2=createTupledList()
print(l2)

Please help. 请帮忙。

My inputs and error output : 我的输入和错误输出:

C:\Users\vikranth\myproject\Python\Lists\Day 0>py tuplesortlist.py
Add an element for the tuple ? y/n :
y
Enter the tuple element :
1
Add an element for the tuple ? y/n :
y
Enter the tuple element :
2
Traceback (most recent call last):
  File "tuplesortlist.py", line 19, in <module>
    l2=createTupledList()
  File "tuplesortlist.py", line 12, in createTupledList
    l=l.append(tuple(i))
AttributeError: 'NoneType' object has no attribute 'append'

The append() function does not return an appended list, it returns a NoneType because it performs the append in place , so you can simply change the line: append()函数不会返回附加列表,它会返回NoneType因为它会在原地执行附加操作,因此您可以简单地更改以下行:

l=l.append(tuple(i))

to: 至:

l.append(tuple(i))

and this should work. 这应该工作。

Code to add multiple elements into a tuple and to add multiple tuples to a list. 将多个元素添加到一个元组并将多个元组添加到一个列表的代码。

"""
Create the tuples into a list.
"""

def createTupledList() :
    l=[]
    while True:
      t=tuple()
      print("Add an element for the tuple ? y/n : ")
      if input()!='y':
        break
      else:
        print("Keep adding the tuple elements : (x to break)")
        while True:
          i=input()
          if i=='x':
            break
          else:
            t+=(i,)
          print(t)
        l.append(t)
    return l

l2=createTupledList()
print(l2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM