【问题标题】:How to save user inputs in a for loop as an integer and string如何在 for 循环中将用户输入保存为整数和字符串
【发布时间】:2021-02-27 20:55:28
【问题描述】:

用户想要输入如下数据并将 N 保存为整数列表,将 B 保存为字符串列表。

输入:

2
hello world
3
how are you
5
what are you doing man

然后我想像下面这样保存这两个列表:

N=[2,3,5]
B=['hello world','how are you','what are you doing man']

我从下面的代码开始,但我不确定如何将其放入循环中以保存所有代码。

N=list(map(int, input()))
B = list(map(str, input().split())) 

【问题讨论】:

    标签: python string list for-loop user-input


    【解决方案1】:

    实时python记事本怎么样:

    N = []
    B = []
    i = 0
    while True:
        lst = B if i % 2 else N
        i += 1
        text = input()
        lst.append(text)
        if lst:
            if not text and not lst[-1]:
                lst.pop()
                break
    N = list(map(int, N))
    print(N)
    print(B)
    

    只需运行上面的代码,然后键入,直到按两次没有其他字符的 ENTER。 输入:

    2
    hello world
    3
    how are you
    5
    what are you doing man
    
    

    输出:

    [2, 3, 5]
    ['hello world', 'how are you', 'what are you doing man']
    

    【讨论】:

      【解决方案2】:

      一种方法非常简单明了。 while 循环可用于保持提示滚动,直到给出存在命令(在本例中为:x)。

      例子:

      N, B = [], []
      
      while True:
          print('Enter an integer, then string (or [x] to exit):')
          n = input()
          if n != 'x':
              N.append(int(n))
              B.append(input())
          else:
              break
      

      提示:

      Enter an integer, then string (or [x] to exit):
      5
      Hello.
      Enter an integer, then string (or [x] to exit):
      15
      How are you?
      Enter an integer, then string (or [x] to exit):
      20
      Very well, thank you.
      Enter an integer, then string (or [x] to exit):
      x
      

      输出:

      N
      >>> [5, 15, 20]
      
      B
      >>> ['Hello.', 'How are you?', 'Very well, thank you.']
      

      【讨论】:

        【解决方案3】:

        您可以执行以下操作:

        N, B = lists = [], []
        
        for i in range(6):
            lists[i%2].append(input())
        
        N = list(map(int, N))
        

        或者,也许不那么神秘:

        aux = [input() for _ in range(6)]
        
        N = list(map(int, aux[::2]))
        B = aux[1::2]
        

        【讨论】:

          猜你喜欢
          • 2020-12-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-05-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多