简体   繁体   中英

How to check the uniqueness of lists inside list?

I have this data:

[[prodcutname,price_rate,price,quantity]]

[['phone', '500', 450.0, 1], ['phone', '500', 2250.0, 5], ['camera', '200', 1080.0, 6], ['laptop', '600', 540.0, 1], ['laptop', '600', 540.0, 1],['laptop', '600', 540.0, 1]]

Now, what I need to do is create a new list with only unique elements(products), and add other values of the same product and put them into list. The ideal output would look like:

[['phone','500',2700,6],['camera','220',1080,6],....]

I tried doing this using -

unique_list = ['phone', '500', 450.0, 1]

big_list = []
mylist = []

for i in range(len(larger_list)):
    for j in range(1,len(larger_list)):
        if(larger_list[i][0]==larger_list[j][0]):
            # Getting the sum or prices and number
            #Sum of price
            larger_list[j][2]=larger_list[i][2]+larger_list[j][2]

            #Sum of number
            larger_list[j][3]=larger_list[i][3]+larger_list[j][3]

            #Adding into a new list
            unique_list[0]=larger_list[i][0]
            unique_list[1]=larger_list[i][1]
            unique_list[2]=larger_list[j][2]
            unique_list[3]=larger_list[j][3]

            mylist.append(unique_list)
            big_list.append(mylist)
            mylist = []

return big_list

But ran into a lot of error to no avail. I even tried by putting them into dictionary. How do I go about doing this in Python?

A Dictionary in Python means fairly the same thing as the word Dictionary . This implies, You can so easily lookup the Value of any keyword using the Keyword directly. This is, unfortunately, not possible with a list since lists are numerically indexed. It is thus recommended to first Convert your list into a Dictionary for 2 reasons:
1: Easier Mapping of the given Data to Individual Keys.
2: Processing the Data-Values to obtain your desired result.

As the Result of the Print shows, it is now easier to access any data by using the Key (even within a loop). For example, to get the Price of Phones , You can simply do:
dictList['phone']['price'] which is much more easier than doing something like: flatList[0][2] which is really not so intuitive....

product_list    = [
    ['phone',  '500', 450.0,  1],
    ['phone',  '500', 2250.0, 5],
    ['camera', '200', 1080.0, 6],
    ['laptop', '600', 540.0,  1],
    ['laptop', '600', 540.0,  1],
    ['laptop', '600', 540.0,  1]
]

# CREATE A LIST OF DICTIONARY FROM GIVEN DATA FOR EASIER MAPPING
item        = ["product_name", "price_rate", "price", "quantity"]
dictList    = {}
for data in product_list:
    if data[0] not in dictList:
        dictList[data[0]]   = dict(zip(item, data))
    else:
        tmpD    = dict(zip(item, data))
        dictList[data[0]]["price"]      = float(dictList[data[0]]["price"]) + float(tmpD['price'])
        dictList[data[0]]["quantity"]   = float(dictList[data[0]]["quantity"]) + float(tmpD['quantity'])
        # dictList[data[0]]["price_rate"] = float(dictList[data[0]]["price_rate"]) + float(tmpD['price_rate'])

print(dictList)
## PRINTS:
## {
##  'phone':  {'product_name': 'phone',  'price_rate': '500', 'price': 2700.0, 'quantity': 6.0}, 
##  'camera': {'product_name': 'camera', 'price_rate': '200', 'price': 1080.0, 'quantity': 6}, 
##  'laptop': {'product_name': 'laptop', 'price_rate': '600', 'price': 1620.0, 'quantity': 3.0}
## }

However, if for any reason you need to have your Data as a List, it is also quite easier with a simple list composition like so:

item        = ["product_name", "price_rate", "price", "quantity"]
dictList    = {}
for data in product_list:
    if data[0] not in dictList:
        dictList[data[0]]   = dict(zip(item, data))
    else:
        tmpD    = dict(zip(item, data))
        dictList[data[0]]["price"]      = float(dictList[data[0]]["price"]) + float(tmpD['price'])
        dictList[data[0]]["quantity"]   = float(dictList[data[0]]["quantity"]) + float(tmpD['quantity'])
        # dictList[data[0]]["price_rate"] = float(dictList[data[0]]["price_rate"]) + float(tmpD['price_rate'])

arrayList   = [ list(dVal.values()) for dKey, dVal in dictList.items() ]
print(arrayList)
## PRINTS:
## [
##     ['phone',  '500', 2700.0, 6.0], 
##     ['camera', '200', 1080.0, 6], 
##     ['laptop', '600', 1620.0, 3.0]
## ]

You can use itertools.groupby in Python3:

import itertools
s = [['phone', '500', 450.0, 1], ['phone', '500', 2250.0, 5], ['camera', '200', 1080.0, 6], ['laptop', '600', 540.0, 1], ['laptop', '600', 540.0, 1],['laptop', '600', 540.0, 1]]
new_s = [(a, list(b)) for a, b in itertools.groupby(sorted(s, key=lambda x:x[0]), key=lambda x:x[0])]
final_s = [[a, b[0][1], *list(map(sum, list(zip(*[i[2:] for i in b]))))] for a, b in new_s]

Output:

[['camera', '200', 1080.0, 6], ['laptop', '600', 1620.0, 3], ['phone', '500', 2700.0, 6]]

you can build a dict :

>>> l
[['camera', '200', 1080.0, 6], ['laptop', '600', 540.0, 1], ['laptop', '600', 540.0, 1], ['laptop', '600', 540.0, 1], ['phone', '500', 450.0, 1], ['phone', '500', 2250.0, 5]]
>>> for i in l:
...     if i[0] in d:
...             d[i[0]].append(i[1:])
...     else:
...             d[i[0]]=[i[1:]]
... 
>>> d
{'phone': [['500', 450.0, 1], ['500', 2250.0, 5]], 'laptop': [['600', 540.0, 1], ['600', 540.0, 1], ['600', 540.0, 1]], 'camera': [['200', 1080.0, 6]]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM