我有一个列表,我想向列表中的每个值添加一个整数,超过第五个值。
PageNumbers = [30, 50, 80, 120, 160, 200, 240, 280]
PageNumbers = [x+100 for x in PageNumbers]
如何实现 PageNumbers = if PageNumber[index] > 5, then [x+100 for x in PageNumbers] else PageNumber[index]
。
我想要的输出是 [30, 50, 80, 120, 160, 300, 340, 380]
最佳答案
查看 enumerate
以在迭代列表时获取索引和值。
这将允许您执行如下操作:
PageNumbers = [30, 50, 80, 120, 160, 200, 240, 280]
PageNumbers = [val + 100 if idx > 4 else val for idx, val in enumerate(PageNumbers)]
*请注意,我实际上使用了 idx > 4
,这意味着超过第 5 个值(基于 0 索引)的任何值,如您在示例中所述和使用的那样。当然,您可以更改为使用您喜欢的任何索引。
在此处查看关于enumerate
的简短帖子和讨论:
Python using enumerate inside list comprehension
关于python - 如何将整数添加到列表中的某些数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54618733/