在Python函数中合并一个while循环

时间:2019-09-13 21:43:47

标签: python-3.x function

对于任何一种编码都是全新的。我想编写一个函数,该函数将返回数字列表的元素,直到第一个偶数。例如,如果列表为[1,5,7,8,9],它将返回[1,5,7]

我知道以下内容不正确,但是我无法将列表传递到while循环中。

def iter_up_to_even(num_lst):
i=0
new_lst=[]
while i < len(num_lst):
    if i%2!=0:
        new_lst.append(num_lst)
        i=i+1
    if i %2==0:
        break 
return new_lst

1 个答案:

答案 0 :(得分:0)

看起来您可能有一些缩进问题。尝试以下解决方案:

const names = ['temp-a-name1', 'temp-a-name2', 'temp-b-name1', 'temp-b-name2'];
const map = names.reduce((map, name) => {
  const key = name.split('-')[1];
  const namesWithKey = map[key] || [];

  return { ...map, [key]: [...namesWithKey, name] };
}, {});

console.log(map);

说明

我们从一个空列表def iter_up_to_even(num_list): to_return = [] current_index = 0 if len(num_list) > 0 else len(num_list) while current_index < len(num_list): if num_list[current_index] % 2 == 1: to_return.append(num_list[current_index]) else: break current_index += 1 return to_return 开始,该列表将在函数末尾返回。接下来,我们遍历输入列表to_return中的每个项目。如果输入列表num_list一开始是空的,那么我们甚至都不会输入while循环(请参阅第3行)。如果该项是奇数,则将其追加到num_list列表中。如果是偶数,我们将退出循环并返回to_return

此外,您应该比较列表中的值(例如to_return),而不是列表中的当前索引(例如num_list[i])。

相关问题