[英]How to join many “listed” tuples into one tuple in Python?
在Python中,關於該問題的答案很少,如何將一個元組列表連接到一個列表中? , 如何在Python中合並兩個元組? , 如何在Python中合並任意數量的元組? 。 所有答案都引用了元組列表 ,因此那里提供的解決方案對我來說似乎毫無用處。
這是我的問題,我有一個列出元組的文件,如下所示:
(1,5)
(5、3)
(10,3)
(5、4)
(1,3)
(2、5)
(1、5)
我想像這樣在一個元組中加入他們:
((1、5),(5、3),(10、3),(5、4),(1、3),(2、5),(1、5))
誰能幫我解決這個問題?
謝謝
tuple(ast.literal_eval(x) for x in my_open_file if x.strip())
我想 ...
a = (1, 5)
b = (5, 3)
c = (10, 3)
d = (5, 4)
e = (1, 3)
f = (2, 5)
g = (1, 5)
tul = (a, b, c, d, e, f, g)
print(tul)
鏈接答案中提到的列表理解也適用於tuple():
print tuple((1,2) for x in xrange(0, 10))
在一開始就放棄“元組”或“列表”將返回一個生成器。
print ((1,2) for x in xrange(0, 10))
用[]代替()是列表的簡寫:
print [(1,2) for x in xrange(0, 10)]
for語句的求值返回一個生成器,而關鍵字或括號告訴python將其解壓縮為該類型。
這是我的問題:我想知道一個元組出現在“結果”中的次數。 所以我這樣做:
from collections import Counter
liste = [1,2,3,5,10]
liste2 = [[1,2,3,5,10], [1,2], [1,5,10], [3,5,10], [1,2,5,10]]
for elt in liste2:
syn = elt # identify each sublist of liste2 as syn
nTuple = len(syn) # number of elements in the syn
for i in liste:
myTuple = ()
if synset.count(i): # check if an item of liste is in liste2
myTuple = (i, nTuple)
if len(myTuple) == '0': # remove the empty tuples
del(myTuple)
else:
result = [myTuple]
c = Counter(result)
for item in c.items():
print(item)
我得到了這些結果:
((1,5),1)
((2,5),1)
((3,5),1)
((5,5),1)
((10,5),1)
((1,2),1)
((2,2),1)
((1,3),1)
((5,3),1)
((10,3),1)
((3,3),1)
((5,3),1)
((10,3),1)
((1,4),1)
((2,4),1)
((5,4),1)
((10,4),1)
我希望有一個元組(key,value),其中value =的數量,而不是N次(例如(( 5,3 ),1)和((10,3),1)出現兩次),次鍵出現在“結果”中。 這就是為什么我認為我可以在使用Counter之前將列出的元組加入一個元組的原因。
我想得到這樣的“結果”:
((1,5),1)
((2,5),1)
((3,5),1)
((5,5),1)
((10,5),1)
((1,2),1)
((2,2),1)
((1,3),1)
((5,3), 2 )
((10,3), 2 )
((3,3),1)
((1,4),1)
((2,4),1)
((5,4),1)
((10,4),1)
謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.