[英]How to read an item in list which is passed as an argument to a calling function?
I am trying to solve a problem in Hacker Rank and stuck below:我正在尝试解决 Hacker Rank 中的一个问题并卡在下面:
When I am trying to insert values to the list it is working fine, but when I am trying remove an item from the list, even though the value is available in list the code in the if block (if str(value) in list1:)
is not getting executed.当我尝试将值插入列表时它工作正常,但是当我尝试从列表中删除一个项目时,即使该值在列表中可用,if 块中的代码(if str(value) in list1:)
没有被执行。
I know I am doing some silly mistakes like passing list in a list.我知道我犯了一些愚蠢的错误,比如在列表中传递列表。 but when I try the same code in just a hardcoded list it is working perfectly fine.但是当我在一个硬编码列表中尝试相同的代码时,它工作得很好。
Example: Sample input:示例:示例输入:
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print
list1=[]
def performListOperations(command, value=None):
if command == "insert":
index, val = value
print("insert " + str(val) + " at Index "+ index)
list1.insert(int(index), int(val))
print(list1)
elif command == "print":
print(list1)
elif command == "remove":
value = value[0]
if str(value) in list1:
print("remove " + str(value) + " from the list:", list1)
list1.remove(value)
print("Value " + str(value) + " does not exist in Array: ", list1)
elif command == "append":
print("Append", list1)
else: print("end.. some more code")
if __name__ == '__main__':
N = int(input())
for i in range(N):
print('Which operation do you want to Perform: "insert", "print", "remove", "append","sort","pop","reverse"')
getcmd, *value = input().split()
print("Command:", getcmd, *value, value)
performListOperations(getcmd, value)
You're inserting integers in the list when you do list1.insert(int(index), int(val))
, not strings.当您执行list1.insert(int(index), int(val))
时,您是在列表中插入整数,而不是字符串。
So you need to use if int(value) in list1:
and list1.remove(int(value))
所以你需要使用if int(value) in list1:
和list1.remove(int(value))
There is a type mismatch.类型不匹配。 The insert is being done using integers, whereas, remove is looking for string type.插入是使用整数完成的,而删除是寻找字符串类型。 Hence, '5' is not found in the list as only 5 [int] is available.因此,在列表中找不到“5”,因为只有 5 [int] 可用。
Handle in one of the place, according to you convenience.根据您的方便,在其中一个地方办理。
below code worked以下代码有效
elif command == "remove":
value = value[0]
print(value, list1)
if int(value) in list1:
print(value)
print("remove " + str(value) + " from the list:", list1)
list1.remove(int(value))
return print(list1)
print("Value " + str(value) + " does not exist in Array: ", list1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.