[英]How do you replace integers in a list with a string in python?
For instance, how would I define a function so that every odd integer in a list is replaced with the string 'odd'? 例如,我将如何定义一个函数,以便将列表中的每个奇数整数都替换为字符串“ odd”? Thanks
谢谢
list = [10 , 11, 12, 13, 14, 15, 16,]
Intended result 预期结果
[10, 'odd', 12, 'odd', 14, 'odd', 16]
I feel like you should probably get the solution on your own, but anyway... 我觉得您可能应该自己获得解决方案,但是无论如何...
result = []
for i in list:
if i % 2 != 0:
result.append('odd')
else:
result.append(i)
Or, maybe something to push you forward: 或者,也许可以推动您前进:
def turn_odd(i):
if i % 2 != 0:
return 'odd'
else:
return i
list = [10 , 11, 12, 13, 14, 15, 16,]
result = map(lambda x: turn_odd(x), list)
一线解决方案可以是:
print [(i,'odd')[i%2] for i in list]
for i in range(len (list)):
if (list[i] % 2 != 0):
list[i] = "odd"
You can use list comprehension: 您可以使用列表理解:
list = [10 , 11, 12, 13, 14, 15, 16]
new_list = [i if i % 2 == 0 else "odd" for i in list]
Here's a good example of how it works: if/else in Python's list comprehension? 这是一个很好的示例: Python列表理解中的if / else?
First note that list
is reserved for the type list in Python, so I will use my_list
instead. 首先请注意,
list
是为Python中的类型列表保留的,因此我将使用my_list
代替。 Then you have three options: 然后,您有三个选择:
A loop with a conditional 有条件的循环
for i in range(0, len(my_list)):
if (i % 2 != 0):
my_list[i] = "odd"
List comprehension (same logic as above) 列表理解(与上述逻辑相同)
my_list = ["odd" if i % 2 != 0 else my_list[i] for i in range(len(my_list))]
A loop without a conditional 没有条件的循环
for i in range(1, len(my_list), 2):
my_list[i] = "odd"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.