[英]Deleting indexes in List based on specific values
我想解決以下問題:
返回數組中數字的總和,返回0表示空數組。 除了數字13是非常不吉利的,因此它不計算在13之后立即出現的數字也不計算。
這就是我所擁有的,這里的想法是13和1(在它之后)被刪除然后剩余的數字相加。 我遇到的問題是刪除部分,實際上並沒有刪除任何內容。 這是語法問題嗎?
x = [1,2,2,1,13,1]
def sum13(nums):
for i in nums:
if i == 13:
del nums[i:i+1]
return sum(nums)
print(sum13(x))
20 <-- should be 6
你的問題與索引有關。 i
是列表中的數字,而不是索引。 這是解決問題的方法:
x = [1,2,2,1,13,1]
def sum13(nums):
for i, num in enumerate(nums):
if num == 13:
del nums[i:i+2] # This removes the index i and the index i+1
return sum(nums)
print(sum13(x))
>>> 6
編輯:正如Thierry Lathuille在評論中提到的,這並沒有充分說明你重復'13'的情況。 假設您想要這種行為,這里有一種方法可以做到:
def sum13(nums):
for i, num in enumerate(nums):
if num == 13:
stop_cut = i + 1
while nums[stop_cut] == 13:
stop_cut += 1
del nums[i:stop_cut+1]
return sum(nums)
只要您循環遍歷列表,只需保留運行總和和前一個值的記錄。 如果i
不是13
並且前一個不是13
添加到總和中無需修改傳入的列表。
def sum13(nums):
sum = 0
last = None
for i in nums:
if i != 13 and last != 13:
sum += i
last = i
return sum
這是具有循環功能的示例。 最長的列表中有13
,我們總結了它之前的所有內容,並sum13
了13
之后的所有內容。
x = [1,2,2,1,13,1]
def sum13(nums, first_call=False):
if not first_call and nums[0] != 13:
nums = nums[1:]
if 13 in nums:
return sum(nums[:nums.index(13)]) + sum13(nums[nums.index(13)+1:])
return sum(nums)
print(sum13(x, True)) # -> 6
請注意,此解決方案適用於鄰近的13
秒。
x = [13, 13, 1]
print(sum13(x, True)) # -> 0
一個問題是您使用列表元素值作為索引。 這是使用發電機的解決方案。 首先確定要忽略的值的索引,然后創建一個不包括這些值的新列表。
x = [1,2,2,1,13,1]
def sum13(nums):
def filter13(nums):
for n, i in enumerate(nums):
if i == 13:
yield n
yield n + 1
bad_ix = set(filter13(nums))
new_nums = [x for n, x in enumerate(nums) if n not in bad_ix]
return sum(new_nums)
sum13(x)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.