如何检查列表a是否大于列表b,然后替换i

2024-06-26 15:30:07 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我想创建一个比较列表,其中有一个列表a(旧的\u列表),它包含:

{'name': 'Jesus and Mary', 'sizeslist': ['Low', 'Medium', 'High']}

以及包含

{'name': 'Apple and Juice', 'sizeslist': None}

所以一开始我做的是检查sizeslist的长度是否比列表B长,然后它应该替换它。你知道吗

old_list = [{'name': 'Jesus and Mary', 'sizeslist': ['Low', 'Medium', 'High']}]

while True:
    product = [{'name': 'Apple and Juice', 'sizeslist': None}]

    if product not in old_list:

        a = product['sizeslist']

        if old_list != []:
            old_list_value = old_list[0]['sizeslist']

            if len(old_list_value) < len(a):
                print("Higher than old_list!")
                old_list[0] = product
                break

            elif len(old_list_value) > len(a):
                old_list[0] = product
                break
        else:
            old_list.append(product)

问题是我得到了object of type 'NoneType' has no len(),我的问题是如何改进代码,这样我就不会得到no len()的错误,并且能够只更改sizeslist而不是整个列表。你知道吗

编辑:

old_list = {'name': 'Jesus and Mary', 'sizes': ['Low', 'Medium', 'High']}

while True:
    new_list = {'name': 'Apple and Juice', 'sizes': None}

    try:
        if new_list['sizes'] not in old_list['sizes']:

                if old_list['sizes'] < new_list['sizes']:
                    print("New element!!!")
                    old_list['sizes'] = new_list['sizes']
                    break

                elif old_list['sizes'] > new_list['sizes']:
                    old_list['sizes'] = new_list['sizes']
                    break

        else:
            randomtime = random.randint(5, 10)
            time.sleep(randomtime)
            continue

    except Exception as err:
        logger.error(err)
        randomtime = random.randint(1, 2)
        time.sleep(randomtime)
        continue

Tags: andname列表newlenifproductold
2条回答
if old_list != []:
            old_list_value1 = old_list['sizeslist']
            old_list_value = list(oldlist_value1[0])

            if len(old_list_value) < len(a):
                print("Higher than old_list!")
                old_list[0] = product
                break

            elif len(old_list_value) > len(a):
                old_list[0] = product
                break

这可能有用。还要注意,您正在比较字符串的长度,其中旧的\u列表[0]的长度为3个字符,而None是nothing。尝试将“无”更改为某个值。你知道吗

我假设您想要比较'sizeslist'而不是整个字典。如果是这样,你应该考虑到你的'sizeslist'可能不是list而是None的情况。这里有一个处理方法。你知道吗

a = {'name': 'Jesus and Mary', 'sizeslist': ['Low', 'Medium', 'High']}
b = {'name': 'Apple and Juice', 'sizeslist': None}

listA = a['sizeslist']
listB = b['sizeslist']

if not listB or (listA != None and len(listA) > len(listB)):
    b['sizeslist'] = a['sizeslist']
else:
    print("Nope")

print(b) # -> {'name': 'Apple and Juice', 'sizeslist': ['Low', 'Medium', 'High']}

相关问题 更多 >