比较同一二维列表中两行之间的值,返回它们的百分比增量 - Python

发布于 01-15 21:07 字数 918 浏览 3 评论 0原文

对于此作业,我无法导入任何模块。我有这个列表,

stateList = [['Set', 'state', 2022, 2023, 2024], ['A', 'start', 100, 100, 100],['A', 'end', 110, 100, 90]]

我想将此列表上进行的计算附加到另一个列表,该列表如下所示。这个新列表的变化将以% 为单位。

stateChange = [['Set', 'state', 2022, 2023, 2024], ['A', 'change', 10, 0, -10]]

到目前为止,我有这段代码,它不起作用

stateChange = []

for row in stateList[0:1]:
    stateChange.append(row)

for row in stateList [1:]:
    stateChange.append([])
    for column in row[2:]:
        chg = (((stateList [1][2]) - column)/column)*100
        stateChange[1].append(chg)     

print(stateChange)

它给了我

[['Set', 'state', 2022, 2023, 2024], [0.0, 0.0, 0.0, -9.090909090909092, 0.0, 11.11111111111111], []]

如何解决这个问题?本质上,我试图从同一列但在第二行获取值,并查看其与第一行的百分比变化,然后将其附加到新列表中。

相反,它在 2022 年出现下降,在 2024 年出现上升,这是相反的。我在新列表中附加的第二行的开头得到了三个额外的 0.0。

For this assignment, I cannot import any modules. I have this list

stateList = [['Set', 'state', 2022, 2023, 2024], ['A', 'start', 100, 100, 100],['A', 'end', 110, 100, 90]]

I want to append calculations made on this list to another list, which would look like this. The change in this new list would be in %.

stateChange = [['Set', 'state', 2022, 2023, 2024], ['A', 'change', 10, 0, -10]]

So far I have this code, which is not working

stateChange = []

for row in stateList[0:1]:
    stateChange.append(row)

for row in stateList [1:]:
    stateChange.append([])
    for column in row[2:]:
        chg = (((stateList [1][2]) - column)/column)*100
        stateChange[1].append(chg)     

print(stateChange)

It is giving me

[['Set', 'state', 2022, 2023, 2024], [0.0, 0.0, 0.0, -9.090909090909092, 0.0, 11.11111111111111], []]

How do I get around this? In essence, I am trying to take the value from the same column, but on the second row, and see what its percentage change is from that first row, and then append this to the new list.

Instead, it is showing a drop in 2022, and a climb in 2024, which is the inverse. And I am getting three extra 0.0's in the beginning of that appended second row in the new list.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

鸵鸟症2025-01-22 21:07:42

我不确定列表中第一个元素的重要性是什么,我假设可能有比“A”更多的集合,或者甚至可能比“开始”和“结束”更多的条目,但只有一个开始和结束。我还假设该列表将始终包含每个状态的开始和结束(因此不存在孤立状态)。如果其中任何一个条件不成立,您就必须实施检查并引发异常或某种其他类型的错误处理。

因此,解决方案是首先为每个状态构建一个开始和结束的字典,然后简单地迭代每个状态并计算必要的值。

def get_changes(state_list):
    starts = {}
    ends = {}

    # first build a dictionary of start and end states for each state (A, B, ...)
    for state in state_list:
        if state[1] == 'start':
            starts[state[0]] = state
        elif state[1] == 'end':
            ends[state[0]] = state

    state_changes = []        
    # iterate through each state name
    for state_name in starts.keys():
        # calculate column changes as (end-start)/start*100
        # first two columns are ignored
        column_changes = [
            (ends[state_name][i] - v)/v*100 
            for i, v in enumerate(starts[state_name]) 
            if i > 1
        ]
        # build the state change list
        state_changes.append([state_name, 'change', *column_changes])

    return state_changes

该函数只会返回实际的 ["A", "change", 10, 0, -10] 正如我所说,我不知道第一个值的意义。我相信你能弄清楚如何将它们粘合在一起。

这是代码运行的实时演示

I'm not sure what the significance of the first element of your list is, and I assume there can be more sets than just "A", or maybe even possibly more entries than just "start" and "end", but only one start and end. I also assume that the list will always contain a start and an end for each state (so there are no orphaned states). If any of these conditions are not true, you'll have to implement checks and throw an exception or some other kind of error handling.

So the solution would be to first build a dictionary of starts and ends for each state and then just simply iterate through each state and calculate the necessary values.

def get_changes(state_list):
    starts = {}
    ends = {}

    # first build a dictionary of start and end states for each state (A, B, ...)
    for state in state_list:
        if state[1] == 'start':
            starts[state[0]] = state
        elif state[1] == 'end':
            ends[state[0]] = state

    state_changes = []        
    # iterate through each state name
    for state_name in starts.keys():
        # calculate column changes as (end-start)/start*100
        # first two columns are ignored
        column_changes = [
            (ends[state_name][i] - v)/v*100 
            for i, v in enumerate(starts[state_name]) 
            if i > 1
        ]
        # build the state change list
        state_changes.append([state_name, 'change', *column_changes])

    return state_changes

The function will only return the actual ["A", "change", 10, 0, -10] as I said I don't know the significance of that first value. I'm sure you can figure out how to glue them together.

Here's a live demo of the code running

巨坚强2025-01-22 21:07:41

让我们再添加一组“B”。由于“Set”元素始终是连续且成对的,因此我们可以将 stateList[1:] 转换为迭代器,并使用 zip 在双循环中一起遍历对:

stateList = [['Set', 'state', 2022, 2023, 2024], 
             ['A', 'start', 100, 100, 100],['A', 'end', 110, 100, 90],
             ['B', 'start', 100, 100, 100],['B', 'end', 110, 100, 90]]

out = [stateList[0]]
it = iter(stateList[1:])
for lst1, lst2 in zip(it, it):
    tmp = [lst1[0], 'change']
    tmp.extend([(y-x)/x*100 for x, y in zip(lst1[2:], lst2[2:])])
    out.append(tmp)

输出:

[['Set', 'state', 2022, 2023, 2024],
 ['A', 'change', 10.0, 0.0, -10.0],
 ['B', 'change', 10.0, 0.0, -10.0]]

Let's add one more set "B". Since "Set" elements are always consecutive and in pairs, we could convert stateList[1:] to an iterator and use zip to traverse pairs together in a double-loop:

stateList = [['Set', 'state', 2022, 2023, 2024], 
             ['A', 'start', 100, 100, 100],['A', 'end', 110, 100, 90],
             ['B', 'start', 100, 100, 100],['B', 'end', 110, 100, 90]]

out = [stateList[0]]
it = iter(stateList[1:])
for lst1, lst2 in zip(it, it):
    tmp = [lst1[0], 'change']
    tmp.extend([(y-x)/x*100 for x, y in zip(lst1[2:], lst2[2:])])
    out.append(tmp)

Output:

[['Set', 'state', 2022, 2023, 2024],
 ['A', 'change', 10.0, 0.0, -10.0],
 ['B', 'change', 10.0, 0.0, -10.0]]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文