TypeError:只能连接列表(不是"元组")到列表((Python))

时间:2014-04-03 00:04:44

标签: python list tuples

在小脚本中运行以下代码时,出现以下错误:

Traceback (most recent call last):
  File "/Users/PeterVanvoorden/Documents/GroepT/Thesis/f_python_standalone/python_files/Working_Files/testcase.py", line 9, in <module>
    permutations_01.determin_all_permutations()
  File "/Users/PeterVanvoorden/Documents/GroepT/Thesis/f_python_standalone/python_files/Working_Files/permutations_01.py", line 8, in determin_all_permutations
    config.permutations = [[1] + x for x in config.permutations]
TypeError: can only concatenate list (not "tuple") to list

代码:

import itertools
import config

def determin_all_permutations():
    L = list(xrange(config.number))
    List = [x+2 for x in L]
    config.permutations = list(itertools.permutations(List,config.number))
    config.permutations = [[1] + x for x in config.permutations]


def determin_lowest_price_permutation():
    length = len(L)
    a = 1
    while a <= length:
        point_a = L[a]
        point_b = L[a+1]

# Array with data cost connecting properties will exist of:
# * first column = ID first property [0]
# * second column = ID second property [1]
# * third column = distance between two properties [2]
# * forth column = estimated cost [3]

        position  = 0
        TF = False

        if TF == False:
            if point_a == config.properties_array[position][0] and point_b == config.properties_array[position][1] and TF == False:
                config.current_price = config.current_price + config.properties_array[position][3]
                config.current_path = config.current_path + [config.properties_array[position][2]]
                TF = True

            else:
                position += 1

        else:
            position = 0
            TF = False

我不明白为什么会出现这种错误。当我测试第8行时

config.permutations = [[1] + x for x in config.permutations]

在正常情况下,在Shell中为ex:

创建一个列表
List = [1,1,1],[1,1,1]
([1,1,1],[1,1,1])
List = [[0] + x for x in List]
List
([0,1,1,1],[0,1,1,1])

它可以工作,但是当在方法中使用完全相同的代码时,我会收到有关添加元组的错误... Isn&#39; t [1]列表?

有人能帮助我吗?

谢谢!

1 个答案:

答案 0 :(得分:3)

在shell上执行的操作中,List由列表[1,1,1][1,1,1]组成,而不是元组。因此,List = [[0] + x for x in List]无误地工作。

在代码中,list(itertools.permutations(List,config.number))返回元组列表,如:

[(2, 4, 8, 5, 11, 10, 9, 3, 7, 6), (2, 4, 8, 5, 11, 10, 9, 6, 3, 7),...]

解释了错误。

这样做:

config.permutations = [[1] + list(x) for x in config.permutations]

解决了这个问题。