[英]How to write function that take a list and number X .If X exist in list in index ‘m’, it should return sum of elements of list from index ‘m’
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))
上面是 function 從索引 m 中找到所有數字和總和。 它從用戶那里獲取一個數字,獲取索引並打印索引 m 中的數字的總和。 但在這種情況下,代碼 output 為 0
嘗試:
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)
Output:
Enter a list of numbers: 10 20 30 40 50 60
Enter a number present in the list: 30
180
首先,您可以使用帶有空參數的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
將字符串轉換為 integer 列表。 然后如果x==i
我在列表中搜索 x 的索引,並從索引開始使用for loop
再次對數字求和。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.