Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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 如何将嵌套列表中除第一个元素外的字符串元素转换为整数_Python_List_Nested - Fatal编程技术网

Python 如何将嵌套列表中除第一个元素外的字符串元素转换为整数

Python 如何将嵌套列表中除第一个元素外的字符串元素转换为整数,python,list,nested,Python,List,Nested,我有以下清单: 输入:templast=[['Resource','0','3',],['read','0','0','0']] 输出应该是这样的 输出:[['Resource',0,3,7],'read',0,0,5]] 我想将所有字符串转换为整数,但Templist中每个列表的第一个元素除外 >>> [sublist[:1] + [int(x) for x in sublist[1:]] for sublist in Templist] [['Resource', 0, 3

我有以下清单:

输入:
templast=[['Resource','0','3',],['read','0','0','0']]

输出应该是这样的

输出:
[['Resource',0,3,7],'read',0,0,5]]

我想将所有字符串转换为整数,但Templist中每个列表的第一个元素除外

>>> [sublist[:1] + [int(x) for x in sublist[1:]] for sublist in Templist]
[['Resource', 0, 3], ['read', 0, 0, 0]]
或者,在Python 2中,我会使用
map

>>> [sublist[:1] + map(int, sublist[1:]) for sublist in Templist]
[['Resource', 0, 3], ['read', 0, 0, 0]]
我还假设神奇出现的7和5是你的打字错误

newlist = [[int(element) if element.isdigit() else element for element in sub] for sub in Templist]
我相信这就是你想要的。这是假设您显示的
'7'
'5'
是因为您不小心将它们从
模板列表中漏掉了。如果除第一个字符串之外的其他字符串之一不是整数,则也不会有错误。

这可能会起作用:

def processList (aList):
    finalList = []
    for aListEntry in aList:
        finalListEntry = []
        for aListEntry_entry in aListEntry:
            try:
                finalListEntry.append(int(aListEntry_entry)
            except:
                finalListEntry.append(aListEntry_entry)
        finalList.append(finalListEntry)
    return finalList
或:

或:


7
5
是从哪里来的?它们是打字错误吗?答案给出了你所要求的,不过只是一个小小的建议,如果圣殿骑士不是一个输入和你创建的东西(带有附加或其他),你应该尝试从一开始就将这些值作为整数添加,而不是稍后尝试转换它们。如果它是一个外部数据,你不需要遵循这个建议。可以使用<代码> Salist[(1)]/Cord>,然后你不需要把<代码> [/]>围绕它。“谢谢StefanPochmann,我用你的建议来改进我的答案。”潘查南好,请考虑接受任何帮助你的答案。真的很喜欢通配符,真的不喜欢列表中的流行音乐吗comp@timgeb我曾经用过
[max(a,b).pop(0)表示a+b中的uu]
,你觉得怎么样-但是,是的,我同意这里它不是很好。你愿意有一个非常容易理解的程序,但它所做的只是打印“Hello World!”或者像Gimp这样用机器代码编写的程序吗?我的方法可读性稍差,但它做得更多。
>>> [[head] + list(map(int, tail)) for head, *tail in Templist]
[['Resource', 0, 3], ['read', 0, 0, 0]]
>>> [item[:1] + list(map(int, item[1:])) for item in Templist]
[['Resource', 0, 3], ['read', 0, 0, 0]]
>>> [[item.pop(0)] + list(map(int, item)) for item in Templist]
[['Resource', 0, 3], ['read', 0, 0, 0]]