python在参数中列出

python在参数中列出,python,Python,我做错了什么?我需要在lst中找到int您可以使用列表轻松完成此操作 def intLst(list): nlst=[] for index1 in int(len(list)): for index2 if int(len(list[index1])): list[index1][index2].isdigit() return nlst 对于列表i中的每个嵌套列表,对于该子列表中的每个项目,如果项目的类型是整数:将其附

我做错了什么?我需要在lst中找到int

您可以使用
列表
轻松完成此操作

def intLst(list):
    nlst=[]
    for index1 in int(len(list)):
        for index2 if int(len(list[index1])):
               list[index1][index2].isdigit()
     return nlst
对于列表
i
中的每个嵌套列表,对于该子列表中的每个项目,如果项目的类型是整数:将其附加到列表中


请注意,在原始代码中,不建议使用
列表
作为参数、函数或变量名…

您有多个错误,例如使用
for..if
而不是
for..in
,也只是返回布尔值,因此您可以使用类似这样的列表理解来修复它(不要将
list
作为变量名!!):


@Ironkey给出的答案是正确的!如果您刚刚开始使用python,并且希望在深入理解列表之前更好地理解for循环,那么在代码中对解释进行了注释:

def intLst(myList):
  return [item for sublist in myList for item in sublist if isinstance(item,int)]
但使用python,您可以直接迭代每个列表,而不使用索引:

def intLst(list):
    nlst=[]
    for index1 in range(len(list)): # len() if used properly, will *always* return an integer, so adding the int() is redundant 
        for index2 in range(len(list[index1])): # Also, integers aren't subscriptable, you will need range()
            if type(list[index1][index2]) == int: # isdigit() will only work on strings, using it on an actual integer will return an error
                nlst.append(list[index1][index2])
    return nlst

print(intLst([['five', 6, 7.7], ['eight', 'ten', 3.4, 8] , ['one', 9.5]]))
它们都将打印:

def intLst(lst):
    nlst=[]
    for value1 in lst:
        for value2 in value1:
            if type(value2) == int:
                nlst.append(value2)
    return nlst

print(intLst([['five', 6, 7.7], ['eight', 'ten', 3.4, 8] , ['one', 9.5]]))

也许值得注意,因为它可能会令人惊讶:
isinstance(False,int)
True
不同于
type(False)==int
@MarkMeyer是的,因为
True=1;False=0
所以如果我做得最多的话。append(int(val))这样可以吗?与其直接返回创建一个for loopYes,如果你有任何问题可以问的话,这将非常好。@Ann Zen的扩展答案很好地展示了这个问题的扩展版本!如果这个答案是你想要的,你可以用绿色复选标记接受它来表示你的感激。讽刺的是每个做了一段时间的人都在建议列表理解,但正如@Ann Zen所指出的,在这一点上,这对你来说可能也是一个步骤。这应该告诉你它们的中心地位。
def intLst(list):
    nlst=[]
    for index1 in range(len(list)): # len() if used properly, will *always* return an integer, so adding the int() is redundant 
        for index2 in range(len(list[index1])): # Also, integers aren't subscriptable, you will need range()
            if type(list[index1][index2]) == int: # isdigit() will only work on strings, using it on an actual integer will return an error
                nlst.append(list[index1][index2])
    return nlst

print(intLst([['five', 6, 7.7], ['eight', 'ten', 3.4, 8] , ['one', 9.5]]))
def intLst(lst):
    nlst=[]
    for value1 in lst:
        for value2 in value1:
            if type(value2) == int:
                nlst.append(value2)
    return nlst

print(intLst([['five', 6, 7.7], ['eight', 'ten', 3.4, 8] , ['one', 9.5]]))
[6,8]