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

时间:2018-12-08 19:45:12

标签: python list for-loop

所以我正在考虑创建一个比较列表,其中有一个包含以下内容的列表A(旧列表):

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

和包含的列表B(产品)

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

因此,我一开始所做的就是检查sizelist的长度是否大于list 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()错误,并且只能更改sizelist而不是整个列表。

编辑:

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

2 个答案:

答案 0 :(得分:1)

我假设您要比较'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']}

答案 1 :(得分:0)

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

这可能有效。另请注意,您正在比较字符串的长度,其中old_list [0]的长度为3个字符,而None为空。尝试将“无”更改为某些值。