簡體   English   中英

在python列表中獲取用戶輸入的最有效方法是什么?

[英]What is the most efficient way to take user input in python list?

我的輸入將是以下形式的內容:

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()

如果有人可以幫助我找到執行上述步驟的最有效方法,那將是非常有幫助的。 我進行了一些搜索,並找到了接受輸入的各種替代方案,但我沒有找到解決這個問題的最有效方法。

效率,我的意思是時間復雜度。 當數字很小並且列表的大小也很小時,上述步驟就可以了。 但是我將不得不提供大量更大的數字和更大的列表,從而影響代碼的效率。

這幾乎是最佳選擇。

如果您正在參加編程比賽,那么您的瓶頸將不僅僅是 I/0,而是您的整體 Python 運行時。 它本質上比 C++/java 慢,並且一些在線評委未能在時間限制內正確解釋這一點。

    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) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM