链接多个列表并对其进行排序 python
Linking several list and make it sorted python
我有清单:
productlinks = ['google.com', 'tes.com', 'lol.com']
name = ['google', 'tes', 'lol']
prices = ['$ 125.000,00', '$ 123.000,00','$ 135.000.000,00']
我想相互链接并按价格排序,所以当我排序时它看起来像这样:
productlinks = ['tes.com', 'google.com', 'lol.com']
name = ['tes', 'google', 'lol']
prices = ['$ 123.000,00', '$ 125.000,00','$ 135.000.000,00']
我用zip功能合并了,但是不知道怎么按价格排序
注意:价格为字符串。
使用sort
函数并提供您需要排序的基础的键,您可以对数据进行排序
>>> 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')]
要对压缩所有三个列表后得到的列表进行排序,您可以使用此代码,
import re
new_prices = list(map(lambda text: re.findall("\d+\.\d+", text)[0], prices))
final_list = list(zip(productlinks, name, new_prices))
sorted_list = pd.DataFrame(final_list).sort_values(by = 2).values
我在这里的排序部分使用了pandas
模块。
第一行去掉所有的","和"$" 从价格并将其余部分转换为浮点数。然后将这些新价格 zipped
与其他两个列表进行比较,然后将我们获得的压缩输出转换为列表。
因为 final_list
看起来非常像 table,我将其转换为 pandas
数据框并按价格值列对其进行排序。现在整个数据框已经排序,我使用 .values
.
将其转换为数组
如果要添加"$"可以用下面的代码替换第三行,
sorted_df = pd.DataFrame(final_list).sort_values(by = 2)
sorted_df[2] = "$" + sorted_df[2].astype(str)
sorted_list = sorted_df.values
我有清单:
productlinks = ['google.com', 'tes.com', 'lol.com']
name = ['google', 'tes', 'lol']
prices = ['$ 125.000,00', '$ 123.000,00','$ 135.000.000,00']
我想相互链接并按价格排序,所以当我排序时它看起来像这样:
productlinks = ['tes.com', 'google.com', 'lol.com']
name = ['tes', 'google', 'lol']
prices = ['$ 123.000,00', '$ 125.000,00','$ 135.000.000,00']
我用zip功能合并了,但是不知道怎么按价格排序
注意:价格为字符串。
使用sort
函数并提供您需要排序的基础的键,您可以对数据进行排序
>>> 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')]
要对压缩所有三个列表后得到的列表进行排序,您可以使用此代码,
import re
new_prices = list(map(lambda text: re.findall("\d+\.\d+", text)[0], prices))
final_list = list(zip(productlinks, name, new_prices))
sorted_list = pd.DataFrame(final_list).sort_values(by = 2).values
我在这里的排序部分使用了pandas
模块。
第一行去掉所有的","和"$" 从价格并将其余部分转换为浮点数。然后将这些新价格 zipped
与其他两个列表进行比较,然后将我们获得的压缩输出转换为列表。
因为 final_list
看起来非常像 table,我将其转换为 pandas
数据框并按价格值列对其进行排序。现在整个数据框已经排序,我使用 .values
.
如果要添加"$"可以用下面的代码替换第三行,
sorted_df = pd.DataFrame(final_list).sort_values(by = 2)
sorted_df[2] = "$" + sorted_df[2].astype(str)
sorted_list = sorted_df.values