I have list:
productlinks = ['google.com', 'tes.com', 'lol.com']
name = ['google', 'tes', 'lol']
prices = ['$ 125', '$ 123','$ 135']
I want to linked each other and sorted it by the price, so when i sorted it would be look like this:
productlinks = ['tes.com', 'google.com', 'lol.com']
name = ['tes', 'google', 'lol']
prices = ['$ 123', '$ 125','$ 135']
I have used zip function to merged it, but i dont know how to sort it by the price.
NOTE: the price in a string.
CodePudding user response:
using sort
function and providing the key to on basic of which you need to sort , you can sort data
>>> productlinks = ['google.com', 'tes.com', 'lol.com']
>>> name = ['google', 'tes', 'lol']
>>> prices = ['$ 125', '$ 123','$ 135']
>>>
>>> l = list(zip(productlinks, name, prices))
>>> l.sort(key=lambda x:int(x[2].split()[-1]))
>>>
>>> l
[('tes.com', 'tes', '$ 123'), ('google.com', 'google', '$ 125'), ('lol.com', 'lol', '$ 135')]
CodePudding user response:
you can use the extend
function :
listname.extend(listname)
CodePudding user response:
To sort the list you get after zipping all three lists you can use this code,
data = zip(productlinks, name, prices)
df = pd.DataFrame(data, columns = ["Links", "Name", "Price"])
sorted_indices = df["Price"].str.strip("$").astype(float).sort_values().index
sorted_data = df.iloc[sorted_indices, :].values
I have used the pandas
module for this.
Firstly I convert the zipped output into a pandas
dataframe. From this dataframe, I identify the column that has the price data in it and strip the "$" sign from the prices. Once I have the numeric part of the prices, I convert them all to float, sort them out and get the sorted indices. I then pass this list of sorted indices in the iloc function and do .values
on it to get the output as a numpy array.