Lambda函数用于将列表中的每个元素与1到10之间的随机数相乘?

哈姆扎·艾哈迈德(Hamza Ahmad)

因为我对python中的函数编程还很陌生,所以我一直坚持这个问题。任何帮助,将不胜感激!

注意:我知道使用map更简单,因为我们可以使用iterable,但是我只需要使用lambda函数来完成此操作。

Given the following list, ages of 25 people:
ages = [79, 91, 25, 22, 95, 69, 47, 87, 87, 2, 13, 94, 50, 73, 29, 87, 81, 51, 32, 69, 10, 91, 45, 7,
51]
Q: Make a new list in which you multiply each age with a random number between 1 to 10
(Generate a random number for each age and multiply them together). Only use Lambda
Function for the multiplication. (You can use random generator provided by in python to
generate the random numbers)

这是我到目前为止所拥有的:

import random

inconsistent = []
ages = [79, 91, 25, 22, 95, 69, 47, 87, 87, 2, 13, 94, 50, 73, 29, 87, 81, 51, 32, 69, 10, 91, 45, 7,
51]

for i in range(25):
    inconsistent.append(random.randint(1,10))
print(inconsistent)
    
x = lambda a,b: a*b
x(ages, inconsistent)

以下是我得到的错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-24-646727e92091> in <module>
     10 
     11 x = lambda a,b: a*b
---> 12 x(ages, inconsistent)

<ipython-input-24-646727e92091> in <lambda>(a, b)
      9 print(inconsistent)
     10 
---> 11 x = lambda a,b: a*b
     12 x(ages, inconsistent)

TypeError: can't multiply sequence by non-int of type 'list'
Epsi95

使用mapMap可以lambda作为第一个参数,而可以iterable作为第二个参数。

ages = [79, 91, 25, 22, 95, 69, 47, 87, 87, 2, 13, 94, 50, 73, 29, 87, 81, 51, 32, 69, 10, 91, 45, 7,
51]

print(list(map(lambda x: x * random.randint(1,10), ages)))
[553, 91, 175, 198, 285, 345, 470, 174, 87, 10, 91, 752, 50, 730, 261, 261, 567, 204, 160, 552, 90, 364, 135, 70, 51]

就你而言

import random

inconsistent = []
ages = [79, 91, 25, 22, 95, 69, 47, 87, 87, 2, 13, 94, 50, 73, 29, 87, 81, 51, 32, 69, 10, 91, 45, 7,
51]

for i in range(25):
    inconsistent.append(random.randint(1,10))
print(inconsistent)
    
x = lambda a,b: a*b

output = []

for i in range(25):
    output.append(x(ages[i], inconsistent[i]))
    
print(output)
[7, 7, 5, 5, 3, 5, 5, 10, 10, 9, 9, 7, 3, 8, 7, 5, 1, 10, 5, 2, 5, 5, 2, 9, 3]
[553, 637, 125, 110, 285, 345, 235, 870, 870, 18, 117, 658, 150, 584, 203, 435, 81, 510, 160, 138, 50, 455, 90, 63, 153]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

生成1到10个Java之间的随机数

生成1到10之间的唯一随机数?

Excel 中 1 到 10 之间的随机数,直到选择所有数字

Python中0到1之间的随机数

将函数应用于列表中的每个元素到另一个列表中的每个元素

如何为我的3D列表中的每个元素= 1分配一个随机数?

Haskell 函数将列表中的元素相乘

将RDD中的每个元素与列表中的相应元素相乘

随机数介于1到49之间的有序列表

c ++如何生成1到10 ^ 6之间的随机数?

使用特定字符串生成 1 到 10 之间的两个随机数

如何使用 graphics2D 显示 1 到 10 之间的随机数?

在Bash Shell脚本中生成1到10之间的随机数

使用php生成1到10之间的30个随机数

将函数应用于列表中的每个元素

生成10到65之间的随机数

无法生成 0 到 10 之间的随机数

创建函数以在SQL中返回1000到10000之间的随机数

如何防止将值以错误的顺序传递到列表中,以及如何将随机数附加到每个值上?

生成1到100之间的唯一随机数

生成 1 到 999 之间的随机数

产生0到1之间的随机数

如何生成1到一百万之间的随机数?

如何在Google表单中显示1到4之间的随机数?

C++中0到1之间的Box muller随机数

创建一个函数,将n <5的值替换为1到4之间的一个随机数(整数)

在Java中获得0到0.06之间的随机数?

将函数应用于3个元组列表中的每个元素,以获得1个结果列表python3

如何在Java中获取40个随机数,范围从1到10?