how to add value to a tuple?

后端 未结 8 1652
别那么骄傲
别那么骄傲 2020-12-08 03:43

I\'m working on a script where I have a list of tuples like (\'1\',\'2\',\'3\',\'4\'). e.g.:

list = [(\'1\',\'2\',\'3\',\'4\'),
        (\'2\',\         


        
相关标签:
8条回答
  • 2020-12-08 04:27

    As other people have answered, tuples in python are immutable and the only way to 'modify' one is to create a new one with the appended elements included.

    But the best solution is a list. When whatever function or method that requires a tuple needs to be called, create a tuple by using tuple(list).

    0 讨论(0)
  • 2020-12-08 04:30
        list_of_tuples = [('1', '2', '3', '4'),
                          ('2', '3', '4', '5'),
                          ('3', '4', '5', '6'),
                          ('4', '5', '6', '7')]
    
    
        def mod_tuples(list_of_tuples):
            for i in range(0, len(list_of_tuples)):
                addition = ''
                for x in list_of_tuples[i]:
                    addition = addition + x
                list_of_tuples[i] = list_of_tuples[i] + (addition,)
            return list_of_tuples
    
        # check: 
        print mod_tuples(list_of_tuples)
    
    0 讨论(0)
提交回复
热议问题