buh*_*htz 2 python tuples list python-3.x
这里的代码适合我.但我是Python的新手,想知道并了解是否有更优雅或pythonic的方式来完成这项工作.
有一个包含两元素元组的列表.我想加入相等的列表元素并将相等元素的数量存储为第三个元组元素(在其他两元组元素前面的第一个).
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
org = [ ( 12, 4 ),
( 8, 4 ),
( 12, 8 ),
( 12, 8 ) ]
# should result in
# [ ( 1, 12, 4 ),
# ( 1, 8, 4 ),
# ( 2, 12, 8 ) ]
def count_element(count_in, e):
"""
How often does 'e' appear in 'count_in'.
"""
count = 0
for x in count_in:
if x == e:
count += 1
return count
def has_element(look_in, e):
"""
'look_in' is a three-element tuple
'e' is a two-element tuple
"""
for x, y, z in look_in:
if y == e[0] and z == e[1]:
return True
return False
def main():
result = []
for i in org:
if has_element(result, i):
continue
c = count_element(org, i)
resi = (c, i[0], i[1])
result += [resi]
print(org)
print(result)
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
与其他答案类似,但对于任何元组维度:
org = [(12, 4), (8, 4), (12, 8), (12, 8), (4, 3, 2, 1)]
from collections import Counter
[(count,) + item for item, count in Counter(org).items()]
# [(2, 12, 8), (1, 12, 4), (1, 4, 3, 2, 1), (1, 8, 4)]
Run Code Online (Sandbox Code Playgroud)
Counter对于这个来说绝对是非常有用的(并且是惯用的),但是记住用平面构造类似结构很容易dict:
counter = dict()
for item in org:
if item not in counter:
counter[item] = 1
else:
counter[item] += 1
# Alternatively, just: counter[item] = counter.get(item, 0) + 1
Run Code Online (Sandbox Code Playgroud)
它的属性非常适合这项任务.如果你不熟悉dicts,那么等待你的更多惊喜.:)
| 归档时间: |
|
| 查看次数: |
618 次 |
| 最近记录: |