【问题标题】:What is the most efficient way to take user input in python list?在 python 列表中获取用户输入的最有效方法是什么?
【发布时间】:2020-07-10 17:54:55
【问题描述】:

我的输入将是以下形式:

10
3 6 7 5 3 5 6 2 9 1
2 7 0 9 3 6 0 6 2 6

这里 10 是元素的总数。后跟两个单独列表的两行输入。

我正在使用以下几行来获取输入:

n=int(input())
m=list(map(int,input().split()))[:n]
q=list(map(int,input().split()))[:n]

此外,我将使用它们对它们进行排序

m.sort()
q.sort()

如果有人可以帮助我找到执行上述步骤的最有效方法,那将是非常有帮助的。 我进行了一些搜索并找到了各种接受输入的替代方案,但我没有找到解决这个问题的最有效方法。

效率是指时间复杂度。当数字很小并且列表的大小也很小时,上述步骤很好。但是我必须提供很多更大的数字和更大的列表,从而影响代码的效率。

【问题讨论】:

  • 您是否发现了性能问题,或者您只是在想像?

标签: python list performance time-complexity


【解决方案1】:

这是最优化的。

如果您参加编程比赛,您的瓶颈将不仅仅是 I/0,而是您的整个 Python 运行时。它本质上比 C++/java 慢,一些在线评委在时限内未能正确解释这一点。

【讨论】:

  • @dark_panda 如果您觉得它有帮助,请点赞/接受,以便未来的观众知道去哪里看。
  • 谢谢。事实上,这是一场编程比赛。上面的部分后面是一个嵌套循环,并且还包含许多 if-else 语句。我得到了一个部分正确的解决方案(通过了 10 个测试用例中的 6 个)。因此一直在寻找一种更有效的方法。
【解决方案2】:
    We often encounter a situation when we need to take number/string as input from user. In this article, we will see how to get as input a list from the user.

    Examples:

    Input : n = 4,  ele = 1 2 3 4
    Output :  [1, 2, 3, 4]

    Input : n = 6, ele = 3 4 1 7 9 6
    Output : [3, 4, 1, 7, 9, 6]

    Code #1: Basic example


<!-- language: lang-phyton -->

    # creating an empty list 
    lst = [] 

    # number of elemetns as input 
    n = int(input("Enter number of elements : ")) 

    # iterating till the range 
    for i in range(0, n): 
        ele = int(input()) 

        lst.append(ele) # adding the element 

    print(lst) 


    Code #2: With handling exception


<!-- language: lang-phyton -->
    # try block to handle the exception 
    try: 
        my_list = [] 

        while True: 
            my_list.append(int(input())) 

    # if input is not-integer, just print the list 
    except: 
        print(my_list) 



    Code #3: Using map()


<!-- language: lang-phyton -->
    # number of elements 
    n = int(input("Enter number of elements : ")) 

    # Below line read inputs from user using map() function  
    a = list(map(int,input("\nEnter the numbers : ").strip().split()))[:n] 

    print("\nList is - ", a) 


    **Code #4: List of lists as input**


<!-- language: lang-phyton -->
    lst = [ ] 
    n = int(input("Enter number of elements : ")) 

    for i in range(0, n): 
        ele = [input(), int(input())] 
        lst.append(ele) 

    print(lst) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    • 2011-10-08
    • 1970-01-01
    • 2019-10-05
    • 2017-06-30
    • 2018-03-04
    相关资源
    最近更新 更多