【问题标题】:Nested list,what's list sizes varies Python嵌套列表,列表大小因 Python 而异
【发布时间】:2022-01-22 17:01:48
【问题描述】:

任何人都可以帮助我解决这个问题吗?(python) :
我有一个嵌套列表,列表的大小各不相同,例如:list=[[1,2],[3,4,5],[6 ,7,8]] 我想删除例如 4 的元素,然后我想存储包含 4 的列表所以我想存储 3,4,5 ,然后我想从我的嵌套列表中删除这个列表所以它看起来像:list=[[1,2],[6,7,8]] 如果我的新列表(retuuurnnlist)中的任何元素与我的文本中的任何元素相等,则将我的布尔变量返回为 true


text="asd 1 4,5 32fas dst sf"
givennumber=
asd=False
list=[[1,2],[3,4,5],[6,7,8]]
for x in range(len(list)):                           
    for y in range(len(list[x])):                    
        if givennumber == y:                                   
            retuuurnnlist.clear()                            
            retuuurnnlist=x.copy()      
            list.remove(list[x][y])          
            if any(element in text for element in list):  
                asd = True                 

我想得到什么:
retuuurnnlist 打印 [3,4,5]
列表打印 [1,2],[6,7,8]
如果我的新列表(retuuurnnlist)中的任何元素与我的文本中的任何元素相等,asd 变量打印为 true,将我的布尔变量返回为 true

【问题讨论】:

    标签: python list nested


    【解决方案1】:

    以下代码将按预期返回输出

    list=[[1,2],[3,4,5],[6,7,8]]
    n = 4
    asd = False
    text="asd 1 4,5 32fas dst sf"
    returnList=[]
    for i in list:
        if n in i:
            returnList.append(i)
            list.remove(i)
    flat_list = [i for sublist in list for i in sublist]
    if any(str(x) in text for x in flat_list):
        asd = True
    print(list)
    print(returnList)
    print(asd)
    

    【讨论】:

      猜你喜欢
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 2019-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-22
      • 1970-01-01
      相关资源
      最近更新 更多