简体   繁体   English

如何在python中用字符串替换列表中的整数?

[英]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.

相关问题 用字符串 Python 替换列表中的整数 - Replace integers in a list with a string Python 如何替换和反转python中的字符串? - How do you replace and reverse a string in python? 在python中,如何打印步骤列表以将整数列表转换为提供的第二个整数列表? - In python, how do you print a list of steps to transform a list of integers into a provided second list of integers? Python - 如何用另一个列表中的字符串值替换列表中存储的字符串的值? - Python - How do you replace the values of strings stored in a list with the string values from another list? 如何将整数和字符串列表更改为 python 中的整数和浮点数列表? - How do you change a list of integers and strings into a list of integers and floats in python? 如何用两个相同的字符串替换列表中的字符串? - How do you replace a string in a list with two of the same string? 如何在Python中将list / pyodbc.row转换为字符串,以便可以使用str.replace? - How do you convert a list/pyodbc.row to a string in python so that str.replace can be used? 如何将整数列表转换为字符串 - Python - How do I convert a list of integers to a string - Python 用python中的字符串替换整数 - Replace integers with a string in python 在python中,你如何接受整数作为参数? - In python, how do you accept integers as parameters?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM