【问题标题】:Is it possible to keep input query to 1 line (Python 3)是否可以将输入查询保留为 1 行(Python 3)
【发布时间】:2017-11-25 17:23:27
【问题描述】:

刚刚学习 Python 3,做函数构建。我有一组函数,它们从用户那里获取多个元素并输出独特的元素。我想知道我是否可以改善程序的外观,因为如果有大量输入它们链接在一起,一个接一个,每个都在一个新的行上。理想情况下,每次用户点击输入时,输入行都会获取元素,并且同一行会重置下一个值。

这是我所拥有的:

userlist = []
uniquelist = []

def make_list(list): #function to assign only unique list values
    for u in userlist:
        if u not in uniquelist:  #only append element if it already appears
            uniquelist.append(u)
        else:
            pass
    print("The unique elements in the list you provided are:", uniquelist)


def get_list():  #get list elements from user
    i = 0
    while 1:
        i += 1  #start loop in get values from user
        value = input("Please input some things: ")
        if value == "":  #exit inputs if user just presses enter
            break
        userlist.append(value)  #add each input to the list
    make_list(userlist)

get_list()

输出(在 Jupyter Notebook 中)添加了请输入一些内容:用户输入的每个元素的行。 50 个输入,50 条线路;看起来邋遢。我找不到让该函数多次使用单行的方法。

【问题讨论】:

  • 省略提示即可。您可以使用iter 函数将while 循环替换为for value in iter(input, ""): userlist.append(value),或者简单地使用userlist = list(iter(input, ""))

标签: python python-3.x input user-input


【解决方案1】:

您只需要使用 map 函数在一行中获取输入,然后拆分每个数据,然后将其类型转换为 map 对象,然后将其传递给 list 函数,该函数将在变量中返回一个列表,如下所示:

var = list(map(int,input().split()))

【讨论】:

  • 这是 Python 3:raw_input 不存在,map 创建一个迭代器而不是返回一个列表(当然不是数组)。
  • 对不起,我没有看到它被要求使用 python3,我更正了它,所以现在它可以在 python 3.x 中使用
  • 也许我没有正确解释(询问)。用户输入一些东西并按下回车键。然后给他们另一个提示。在空白时按 enter 会中断输入循环。我希望找到一种方法让 Python 不再继续呈现新行,而是每次都重复提供相同的行。
【解决方案2】:

您想在每次输入后清除控制台中的文本吗?然后您可以在 Windows 上使用 os.system('CLS') 或在 Unix 系统上使用 os.system('clear')

import os

os.system('CLS')
user_input = ''
while user_input != 'quit':
    user_input = input('Input something:')
    os.system('CLS')  # Clear the console.
    # On Unix systems you have to use 'clear' instead of 'CLS'.
    # os.system('clear')

或者,我认为您可以使用curses

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    • 2018-07-03
    • 2020-07-27
    • 2021-04-08
    • 2011-07-06
    • 1970-01-01
    相关资源
    最近更新 更多