python中10个整数放列表_将K添加到Python整数列表中的每个元素

在数据分析中,有时有必要在python列表中的每个元素上添加一些值,以判断新场景的结果。这有助于测试多个场景,以了解数据集在不同值下的行为,因此可以创建一个可以处理这些场景的模型或算法。在本文中,我们将看到如何处理此要求。

使用列表理解

列表理解是处理列表的一种常规方法,我们在其中遍历列表的每个元素。在下面的示例中,我们使用简单的for循环将相同的数字添加到列表的每个元素。

示例orig_list = [5, 6, 7, 4, 10]

print ("The given list is : " + str(orig_list))

# Use list comprehension

new_list = [n + 5 for n in orig_list]

# printing result

print ("After adding 5 to each element to list : " + str(new_list))

输出结果

运行上面的代码给我们以下结果-The given list is : [5, 6, 7, 4, 10]

After adding 5 to each element to list : [10, 11, 12, 9, 15]

在映射上使用lambda

map和add方法也可以得到相同的结果。Lambda函数对固定的迭代次数重复相同的操作,并且在所有lambda迭代结束后,使用map捕获结果。

示例orig_list = [5, 6, 7, 4, 10]

print ("The given list is : " + str(orig_list))

#Using map() + lambda

new_list= list(map(lambda m : m + 3, orig_list))

print ("After adding i to each element to list : " + str(new_list))

输出结果

运行上面的代码给我们以下结果-The given list is : [5, 6, 7, 4, 10]

After adding i to each element to list : [8, 9, 10, 7, 13]

使用map()和add()

代替lambda运算符,我们还可以将add方法与map一起使用。在下面的示例中,我们创建另一个列表,该列表的元素数量与列表的长度相同,并且包含需要添加的数量。然后我们应用map方法。

示例import operator

orig_list = [5, 6, 7, 4, 10]

print ("The given list is : " + str(orig_list))

# initializing new list

list_with_k_value = [9] * len(orig_list)

# using map() + operator.add

new_list = list(map(operator.add, orig_list, list_with_k_value))

print ("After adding i2 to each element to list : " + str(new_list))

输出结果

运行上面的代码给我们以下结果-The given list is : [5, 6, 7, 4, 10]

After adding i2 to each element to list : [14, 15, 16, 13, 19]

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值