python3 一小段 code 求个简写

2020-11-13 16:29:25 +08:00
 css3

大佬们,下面这小段,有什么简写吗,已被自己蠢哭

# python3

A_one, A_other_one, A_two, A_other_two = A
B_one, B_other_one, B_two, B_other_two = B
... # 会有很多

all = [
    [{ "A_one": A_one, "B_one": B_one },
        { "A_other": A_other_one, "B_other": B_other_one }
    ],
    [{ "A_one": A_two, "B_one": B_two },
        { "A_other": A_other_two, "B_other": B_other_two }
    ]
]
2425 次点击
所在节点    Python
14 条回复
paddistone
2020-11-13 16:35:28 +08:00
k 要是没有意义干嘛不考虑元组;
需求如此的话,这就是最好的实现了,keep simple, keep stupid ;
一点要花里胡哨一点,exec 、eval 了解一下,不建议
RRRoger
2020-11-13 16:38:03 +08:00
你至少得先把这些重复的东西 提取出一个函数吧
chaleaoch
2020-11-13 16:38:38 +08:00
你的意思 A 和 B 会有很多 成对出现吗? 否则你这个代码看不懂.
tairan2006
2020-11-13 16:40:24 +08:00
你这是为了解包?你直接写个数组按索引取不就完了
xchaoinfo
2020-11-13 16:41:19 +08:00
试试这个模块
```python
from collections import namedtuple
```
MaxTan
2020-11-13 16:41:51 +08:00
没看懂为啥要这样写,先把思路捋清楚
css3
2020-11-13 16:49:31 +08:00
@css3 @paddistone @RRRoger @chaleaoch @tairan2006 @xchaoinfo @MaxTan

就是通过 A, B... 生成 all 这个 list, all 里边嵌套 list, 里边又是个 dict, dict 的 key 是固定的
css3
2020-11-13 16:50:01 +08:00
value 根据 A, B unpack 后的值,塞进来
tairan2006
2020-11-13 17:01:55 +08:00
就是按索引处理啊…all = [[] for _ in range(10)],然后遍历 A,把 A 的元素先塞到结果数组里,遍历 B 接着塞
acmore
2020-11-13 17:04:05 +08:00
`namedtuple` or `dataclass`?
ysc3839
2020-11-13 17:05:19 +08:00
按照你给的代码中我发现的规律:

data = {'A': [1,2,3,4], 'B': [5,6,7,8], 'C': [9,0,1,2]}
all = [
[{f'{k}_one': v[0] for k, v in data.items()}, {f'{k}_other': v[1] for k, v in data.items()}],
[{f'{k}_one': v[2] for k, v in data.items()}, {f'{k}_other': v[3] for k, v in data.items()}]
]
imn1
2020-11-14 14:32:16 +08:00
既然 key 固定,变化不定的只是值,那很多解决办法
key 固定的,基本上从 sql 思维考虑就可以了,简单就 namedtuple 、csv,复杂就 pandas.DataFrame,sql 数据库
根据数据来源采用相应方便的方案,然后导出就可以了,可以用 iter() + append
mizai
2020-11-15 23:33:23 +08:00
用 zip 加推导式很容易就可以简化
A = [1,2,3,4]
B = ['a','b','c','d']
C = [random() for i in range(4)]
data_array = [A,B,C] # 可以添加任意长度的数据
keys = ['one','other_one','two','other_two'] # dict 的 key 值固定

all = [dict(zip(column,data_item)) for data_item in zip(*data_array)]
SjwNo1
2020-11-19 13:53:13 +08:00
zip

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/724921

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX