Skip to main content
 首页 » 编程设计

python之将 int 转换为字符串以添加到 map python 的函数

2025年05月04日26lexus

昨天刚开始学python。任务是从中随机生成5种颜色

c=["red", "blue", "green", "yellow", "purple", "orange", "white", "black"] 

所以我用 随机选择(c)

要创建一个 50 的列表,我想创建一个函数,然后使用函数将其添加到 map() 以添加随机颜色并遍历 range(1,51)

基本上将数字 1 2 3 4 等更改为随机选择的颜色。

我不知道如何将数字更改为 random.choice(c) - 那么我可以为 map 使用什么功能,即

print map('function', range(1,51)) 

我考虑过像这样使用 lambda

>>> sums = lambda x:(x-x)+(random.choice(c)) 
>>> print map(sums,range(1,51)) 

但是我得到了,

Traceback (most recent call last): 
  File "<pyshell#15>", line 1, in <module> 
    print map(sums,range(1,51)) 
  File "<pyshell#14>", line 1, in <lambda> 
    sums = lambda x:(x-x)+(random.choice(c)) 
TypeError: unsupported operand type(s) for +: 'int' and 'str' 

但它并没有起作用,因为 im + 一个 int 到字符串

我正在尝试通过文档寻找一些东西,但没有运气

关于我能做什么的任何提示

请您参考如下方法:

你可以得到 50 种颜色:

>>> c = ["red", "blue", "green", "yellow", "purple", "orange", "white", "black"] 
>>> for _ in range(50): 
...     random.choice(c) 
...      
...  
'blue' 
'red' 
'yellow' 
... 

要生成 50 种颜色的列表,请使用列表理解:

>>> colors = [random.choice(c) for _ in range(50)] 
>>> colors 
['green', 'red', 'green', 'orange', 'orange', 'black', 'black', 'purple', 'red', 
 'black', 'yellow', 'yellow', 'white', 'purple', 'orange', 'white', 'red', 'gree 
n', 'black', 'blue', 'orange', 'green', 'orange', 'blue', 'white', 'blue', 'oran 
ge', 'black', 'orange', 'green', 'black', 'green', 'blue', 'orange', 'blue', 'gr 
een', 'green', 'white', 'red', 'green', 'yellow', 'yellow', 'blue', 'orange', 'p 
urple', 'green', 'black', 'yellow', 'black', 'red'] 

你也可以像这样使用map:

>>> map(lambda _: random.choice(c), range(50)) 
['purple', 'yellow', 'black', 'white', 'black', 'black', 'purple', 'red', 'blue' 
, 'white', 'blue', 'white', 'yellow', 'yellow', 'white', 'blue', 'orange', 'whit 
e', 'yellow', 'black', 'green', 'white', 'blue', 'blue', 'yellow', 'red', 'red', 
 'black', 'purple', 'blue', 'yellow', 'yellow', 'green', 'orange', 'purple', 're 
d', 'orange', 'red', 'blue', 'green', 'purple', 'orange', 'red', 'white', 'orang 
e', 'green', 'purple', 'white', 'green', 'green'] 

或者您甚至可以省略 lambda 中的 _:

>>> map(lambda: random.choice(c), range(50)) 

所有版本中的_ 表示未使用的变量。它可以是任何东西,比如 i 或 number。例如,在您的情况下,您从未真正想使用 range 函数产生的数字。这是一个约定。