如何读取列表中作为参数传递给调用函数的项



我正试图解决Hacker Rank中的一个问题,并被困在下面:

当我尝试向列表中插入值时,它可以正常工作,但当我尝试从列表中删除项目时,即使该值在列表中可用,if块(if str(value) in list1:)中的代码也不会执行。

我知道我犯了一些愚蠢的错误,比如在列表中传递列表。但当我在一个硬编码列表中尝试相同的代码时,它运行得非常好。

示例:样本输入:

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)

执行list1.insert(int(index), int(val))时,在列表中插入的是整数,而不是字符串。

所以你需要使用if int(value) in list1:list1.remove(int(value))

存在类型不匹配。插入是使用整数完成的,而remove则是查找字符串类型。因此,在列表中找不到"5",因为只有5[int]可用。

在其中一个地方处理,根据您的方便。

下面的代码工作


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)

相关内容

最新更新