[英]I need to pass a user input variable as this list eg: [1, 3, 6, 4, 1, 2] in below python program. Could some one help me
def solution(A):
sortedset= set(sorted(A))
sol=1
#for i in sortedset
print(sortedset)
for i in sortedset:
if i == sol:
sol+=1
else:
break
print(sol)
A = input()
solution(A)
#A = [1, 3, 6, 4, 1, 2]
''While passing A = input() and input [1,3,6,4,1,2] not getting expected output '5' but if I give instead of user input directly like as A = [1, 3, 6, 4, 1, 2] i'm getting output '5'. ''虽然通过 A = input() 和输入 [1,3,6,4,1,2] 没有得到预期 output '5' 但如果我直接给出而不是用户输入,如 A = [1, 3, 6 , 4, 1, 2] 我得到 output '5'。 Please help me to fix this issue.
请帮我解决这个问题。 ''
''
You can convert the string interpretation of a list that input
returns to a list with ast.literal_eval
:您可以使用
ast.literal_eval
将input
返回的列表的字符串解释转换为列表:
import ast
A = ast.literal_eval(input())
As some people mentioned in the comments, the input function always returns a string.正如一些人在评论中提到的,输入 function 总是返回一个字符串。
However if you can always convert this string into your desired type.但是,如果您始终可以将此字符串转换为所需的类型。 For example:
例如:
A = []
try:
while True:
A.append(int(input()))
# if the input is not-integer, run the function
except:
solution(A)
A = [int(item) for item in input("Enter the list items separated by space: ").split()]
solution(A)
This would work in python2 but not in 3 as the input is python 2's raw input and python 2's input has been removed这将在 python2 中起作用,但在 3 中不起作用,因为输入是 python 2 的原始输入,并且 python 2 的输入已被删除
you could use eval(input()) instead你可以使用 eval(input()) 代替
This is what you want I believe: i) string representation of list -> list ii) elements of list -> int我相信这就是你想要的:i)列表的字符串表示 -> 列表 ii)列表的元素 -> int
import ast
x = '[ "1", "2", "3" , "4", "5"]'
x = ast.literal_eval(x)
x = [int(val) for val in x ]
print(x)
[1, 2, 3, 4, 5]
[1、2、3、4、5]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.