[英]Python calculating percentages from list
Hello i have a list that has the following information that is retrieved from a db您好,我有一个列表,其中包含从数据库中检索到的以下信息
test_list_1 = ['01/01/2022:79.86','02/01/2022:65.86','03/01/2022:600.23','04/01/2022:179.26']
test_list_2 = ['01/01/2022:55.86','02/01/2022:25.75','03/01/2022:300.23']
I would like to be able to produce the following output from that:我希望能够从中生成以下 output:
# Output of test_list_1
01/01/2022 (79.86) => 02/01/2022 (65.86) => Percentage Diff (-17%)
01/01/2022 (79.86) => 03/01/2022 (600.23) => Percentage Diff (+651%)
01/01/2022 (79.86) => 04/01/2022 (179.26) => Percentage Diff (+124%)
02/01/2022 (65.86) => 03/01/2022 (600.23) => Percentage Diff (+811%)
02/01/2022 (65.86) => 04/01/2022 (179.26) => Percentage Diff (+172%)
03/01/2022 (600.23) => 04/01/2022 (179.26) => Percentage Diff (-70%)
# Output of test_list_2
01/01/2022 (55.86) => 02/01/2022 (25.75) => Percentage Diff (-53%)
01/01/2022 (55.86) => 03/01/2022 (300.23) => Percentage Diff (+437%)
02/01/2022 (25.75) => 03/01/2022 (300.23) => Percentage Diff (+1065%)
I am having a lot of trouble even trying to figure out the logic on how to do this.我什至试图弄清楚如何执行此操作的逻辑时遇到了很多麻烦。 If some one can please assist me with just getting started with this that would be amazing.
如果有人可以帮助我开始使用这将是惊人的。
Thank you very much in advance.非常感谢你提前。
A solution that relies on the powerful itertools
module to first generate combinations.依赖强大的
itertools
模块首先生成组合的解决方案。
Applied here on test_list1
.此处应用于
test_list1
。
Just make a function of that to apply to any list in argument.只需制作一个 function 即可应用于参数中的任何列表。
from itertools import combinations
def pdiff(src: float, dst: float) -> float:
return (dst-src)/src*100
combs = [(x,y) for x,y in combinations(test_list_1, 2)]
for x, y in combs:
dtx, percentx = x.split(":")
dty, percenty = y.split(":")
print(f"{dtx} ({percentx}) => {dty} ({percenty}) => Percentage Diff ({pdiff(float(percentx), float(percenty)): .2f}%)")
You have two major hurdles to get from the starting point to the paired off values you need:从起点到您需要的配对值,您有两个主要障碍:
Parsing is fairly simple:解析相当简单:
parsed_list_1 = []
for s in test_list_1:
date, sep, price = s.partition(':')
# Optionally test "if sep:" and raise an error if the data didn't have the expected colon in it
parsed_list_1.append((date, float(price)) # Store a tuple of the date string and parsed prices
Once you've got a parsed list
of date-price tuple
s, since your data is already in sorted order, you can use itertools.combinations
(with import itertools
at the top of the file) to pair up each date's data with each subsequent date, eg:一旦你得到一个日期价格
tuple
的解析list
,因为你的数据已经排序,你可以使用itertools.combinations
(在文件顶部import itertools
)将每个日期的数据与每个后续数据配对日期,例如:
for (start_date, start_price), (end_date, end_price) in itertools.combinations(parsed_list_1, 2):
# Do stuff with each pair of dates and associated prices
I'm leaving it up to you how to compute the percentage difference, adapt the code to work with multiple input list
s without writing the same code twice, format your output, and (if necessary) how to handle sorting the data if it's not guaranteed to be in order by date already, but this is 80% of the work.我将留给您如何计算百分比差异,调整代码以处理多个输入
list
而无需两次编写相同的代码,格式化您的 output,以及(如有必要)如果不是,如何处理数据排序已经保证按日期排序,但这是 80% 的工作。 You could solve it without itertools.combinations
with carefully constructed nested for
loops, eg您可以在没有
itertools.combinations
的情况下使用精心构造的嵌套for
循环来解决它,例如
for i, (start_date, start_price) in enumerate(parsed_list_1, 1):
for end_date, end_price in parsed_list_1[i:]:
# Do stuff with each pair of dates and associated prices
but it's slower, more verbose, and frankly less clear.但它更慢,更冗长,而且坦率地说不太清楚。 The
itertools
module is friggin' magic; itertools
模块是该死的魔法; use it when you can.尽可能使用它。
You can obtain the desired output through a relatively simple set of lists manipulations.您可以通过一组相对简单的列表操作获得所需的 output。 Here is my solution for the first list (it is exactly the same for the second).
这是我对第一个列表的解决方案(第二个列表完全相同)。
test_list_1 =['01/01/2022:79.86','02/01/2022:65.86','03/01/2022:600.23','04/01/2022:179.26']
test_list_1 = [el.split(':') for el in test_list_1]
for index, value in enumerate(test_list_1):
for next_index, next_value in enumerate(test_list_1[index+1:]):
v = 100*(float(next_value[1]) - float(value[1]))/float(value[1])
print(f"{value[0]} ({value[1]}) => {next_value[0]} ({next_value[1]}) => Percentage Diff ({int(v)})%")
Here I am assuming the list elements are strings and you are interested only in printing the output as you reported it.在这里,我假设列表元素是字符串,并且您只对打印报告的 output 感兴趣。
Hope this helps, bless!希望对你有帮助,祝福!
Different solution:不同的解决方案:
lst = ['01/01/2022:79.86','02/01/2022:65.86','03/01/2022:600.23','04/01/2022:179.26']
def pairings(pool):
for i, m in enumerate(pool):
for n in pool[i+1:]:
yield (m, n)
new_list = list(pairings(lst))
for i,j in new_list:
diff = int((float(j.split(":", 1)[1]) - float(i.split(":", 1)[1]))/float(i.split(":", 1)[1])*100)
print(i + " => " + j + " => Percentage Diff " + str(diff) + "%")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.