我正在嘗試解決 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)
uj5u.com熱心網友回復:
當你這樣做時,你在串列中插入整數list1.insert(int(index), int(val)),而不是字串。
所以你需要使用if int(value) in list1:和list1.remove(int(value))
uj5u.com熱心網友回復:
存在型別不匹配。插入是使用整數完成的,而洗掉是在尋找字串型別。因此,在串列中找不到“5”,因為只有 5 [int] 可用。
在一個地方處理,根據您的方便。
uj5u.com熱心網友回復:
下面的代碼有效
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/434861.html
上一篇:Python函式不回傳真或假
