def func(x):
lst=list(map(int,input("Enter a list of numbers: ").split()))
flag=0
num=0
for i in lst:
if x==i:
flag=1
if flag==1:
ab=lst.index(x)
for i in range(ab,len(lst),1):
num=lst.index(ab)
num=num lst[i]
print(num)
return num
y=input("Enter a number present in the list: ")
print(func(y))
以上是從索引 m 中查找所有數字并求和的函式。它從用戶那里獲取一個數字,獲取索引并列印索引 m 中的數字的總和。但在這種情況下,代碼輸出為 0
uj5u.com熱心網友回復:
首先,您可以使用split()空引數。
您的問題的解決方案是:
def func(x):
a=input("Enter list of Numbers: ")
lst=list()
for i in a:
try:
i=int(i)
lst.append(i)
except:
pass
num=0
x=int(x)
for i in (lst):
if x==i:
index=lst.index(x)
for i in range(index,len(lst),1):
num=num lst[i]
return num
y=input("Enter a number present in the list: ")
print(func(y))
而不是map我使用for loop將字串轉換為整數串列。然后,如果x==i我在串列中搜索 x 的索引并從索引開始使用 a 再次對數字求和for loop。
uj5u.com熱心網友回復:
嘗試:
def func(y, lst):
try:
return sum(lst[lst.index(y):])
except ValueError:
print(f"{y} is not in {lst}")
lst = list(map(int,input("Enter a list of numbers: ").split()))
y = int(input("Enter a number present in the list: "))
total = func(y, lst)
print(total)
輸出:
Enter a list of numbers: 10 20 30 40 50 60
Enter a number present in the list: 30
180
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/412386.html
標籤:
