如何加入许多"列出"在Python中将元组组合成一个元组?

时间:2016-02-04 00:41:00

标签: python tuples

in Python, How to join a list of tuples into one list?How to merge two tuples in Python?How To Merge an Arbitrary Number of Tuples in Python?上的问题答案很少。所有的答案都是指元组列表,所以那里提供的解决方案对我来说似乎毫无用处。

这是我的问题,我有一个文件,其元组如下所示:

  

(1,5)

     

(5,3)

     

(10,3)

     

(5,4)

     

(1,3)

     

(2,5)

     

(1,5)

我想加入他们这样的一个元组:

  (p,(1,5),(5,3),(10,3),(5,4),(1,3),(2,5),(1,5))

任何人都可以帮我解决这个问题吗?

由于

4 个答案:

答案 0 :(得分:1)

tuple(ast.literal_eval(x) for x in my_open_file if x.strip())

我想......

答案 1 :(得分:1)

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)

答案 2 :(得分:0)

链接答案中提到的

列表理解也与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将它解压缩到该类型。

答案 3 :(得分:0)

这是我的问题:我想知道一个元组出现在我的结果中的次数'。所以我这样做了:

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)

而不是有一些elts N次(例如((5,3),1)((10,3),1)出现两次),I想要一个元组(键,值),其中value =键出现在'结果'中的次数。这就是为什么我认为在使用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)

由于

相关问题