在python列表中获取用户输入的最有效方法是什么?
我的输入将是以下形式:在python列表中获取用户输入的最有效方法是什么?,python,list,performance,time-complexity,Python,List,Performance,Time Complexity,我的输入将是以下形式: 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() 如果有人能帮我找到执行上述步骤的最有效方法,那将是非常有帮助的。 我做了
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)
示例:
输入:n=4,ele=1234
输出:[1,2,3,4]
输入:n=6,ele=3 4 1 7 9 6
输出:[3,4,1,7,9,6]
代码#1:基本示例
#创建空列表
lst=[]
#作为输入的元素数
n=int(输入(“输入元素数:”)
#迭代到指定的范围
对于范围(0,n)内的i:
ele=int(输入())
lst.append(ele)#添加元素
打印(lst)
代码#2:处理异常
#尝试块来处理异常
尝试:
我的清单=[]
尽管如此:
my_list.append(int(input()))
#如果输入不是整数,只需打印列表
除:
打印(我的列表)
代码#3:使用map()
#元素数
n=int(输入(“输入元素数:”)
#下面的行使用map()函数从用户处读取输入
a=列表(映射(int,输入(“\n输入数字:”).strip().split())[:n]
打印(“\n列表为-”,a)
**代码#4:作为输入的列表列表**
lst=[]
n=int(输入(“输入元素数:”)
对于范围(0,n)内的i:
ele=[input(),int(input())]
第一个附加(ele)
打印(lst)
@dark\u panda如果您觉得它有帮助,请向上投票/接受,以便将来的观众知道该去哪里看。谢谢。事实上,这是一场编程比赛。上面的部分后面是一个嵌套循环,还包含许多if-else语句。我得到了一个部分正确的解决方案(通过了10个测试用例中的6个)。因此,我们正在寻找一种更有效的方法。您是否观察到性能问题,或者您只是在想象一个问题?