Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将列表中的某些元素更改为int_Python_Python 3.x - Fatal编程技术网

Python 将列表中的某些元素更改为int

Python 将列表中的某些元素更改为int,python,python-3.x,Python,Python 3.x,我有一份清单: aList = ['asdf123', '100', '45', '34hello'] 如何更改它,使“100”和“45”变为int而不是str aList = ['asdf123', 100, 45, '34hello'] 你可以使用一个助手函数 def to_int(s): try: return int(s) except: return s aList = [to_int(n) for n in aList] 定义转

我有一份清单:

aList = ['asdf123', '100', '45', '34hello']
如何更改它,使“100”和“45”变为int而不是str

aList = ['asdf123', 100, 45, '34hello']

你可以使用一个助手函数

def to_int(s):
    try:
        return int(s)
    except:
        return s

aList = [to_int(n) for n in aList]

定义转换整数或返回原始值的方法

def tryInt(value):
    try:
        return int(value)
    except:
        return value
然后使用
map
lambda

map( lambda x: tryInt(x), aList )

下面的内容应该能让你达到目的

def convert(x):
    try:
        return int(x)
    except ValueError:
        return x

aList = map(convert, aList)

欢迎来到堆栈溢出!请展示你目前所拥有的。有关更多信息,请参阅。@cricket\u 007删除了有关DUP的注释。第一次调用
int(s)
是没有用的,因为它可以在
return
语句中引发异常。目前,这是唯一一个使用有意义且符合PEP-8的函数名称的答案。干得好。噢,嘘,谢谢:)或列表理解,
[tryInt(n)表示列表中的n]