【问题标题】:I want to get a list of strings from a user, how should i get that?我想从用户那里得到一个字符串列表,我应该怎么得到呢?
【发布时间】:2019-05-23 09:14:51
【问题描述】:

我想从用户那里获取一系列字符串并将其放入列表中然后打印出来

我也想在完成后关闭列表并打印它

list = []
for i in list:

    list[a]=input('the name of stings:')
    list.append(list[a])
    a +=
    print(list)

【问题讨论】:

  • 你打算接受多少次输入?
  • 或者用户不想再输入字符串时输入什么
  • 离题但很重要:不要使用list作为变量名,它会覆盖Python中的list()
  • 请不要使用list作为变量名。此外,您的列表在开始时是空的......所以循环永远不会执行,将其替换为应该执行的时间。
  • 你的代码让我很困惑,你想做什么?什么是a,你为什么要a += sth?为什么要将列表元素附加到自身?您真的是想在list[a] 行中写my_dict[a] 进行查找吗?

标签: python arrays lis


【解决方案1】:

试试这个:

list_ = []
not_done = True
while not_done:
    inp = input('name of string : ')
    if inp.lower() != 'done': # Put any string in stead of 'done' by which you intend to not take any more input
        list_.append(inp)
    else:
        break
print(list_)

输出

name of string : sd
name of string : se
name of string : gf
name of string : yh
name of string : done
['sd', 'se', 'gf', 'yh']

【讨论】:

    【解决方案2】:

    你可以这样做:

    n = int(input())
    
    my_list = list()
    for i in range(n):
        my_str = input('Enter string ')
        my_list.append(my_str)
        print('You entered', my_str)
        print(my_list)
    

    这里是示例(第一行是数字,你想输入多少次):

    4
    Enter string abc
    You entered abc
    ['abc']
    Enter string xyz
    You entered xyz
    ['abc', 'xyz']
    Enter string lmn
    You entered lmn
    ['abc', 'xyz', 'lmn']
    Enter string opq
    You entered opq
    ['abc', 'xyz', 'lmn', 'opq']
    

    【讨论】:

    • ------------------------------------------ --------------------------------- ValueError Traceback(最近一次调用最后一次)() ----> 1 n = int(input()) 2 3 my_list = list() 4 for i in range(n): 5 my_str = input('Enter string') ValueError: invalid literal对于基数为 10 的 int():“阿尔及利亚”
    • 你在第一行输入了什么
    【解决方案3】:
    N = 10  # desired number of inputs
    
    lst = []  # don't use `list` as it's resereved
    for i in range(N):
        lst.append(input('the name of strings: ')
    
    print(lst)
    

    【讨论】:

      【解决方案4】:

      一个例子如下所示:

      input_list = []
      while True:
          your_input = input('Your input : ')
          if your_input.upper() == "DONE":
              break
          input_list.append("%s" % your_input )
      print("%s" % input_list)
      

      输出:

      >>> python3 test.py 
      Your input : a
      Your input : b
      Your input : c
      Your input : d
      Your input : dOnE
      ['a', 'b', 'c', 'd']
      

      【讨论】:

        猜你喜欢
        • 2014-11-19
        • 1970-01-01
        • 2020-09-21
        • 2013-11-12
        • 2020-12-02
        • 1970-01-01
        • 2020-08-22
        • 1970-01-01
        • 2022-11-15
        相关资源
        最近更新 更多