Pet*_*den 4 python tuples list
在小脚本中运行以下代码时,出现以下错误:
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
Run Code Online (Sandbox Code Playgroud)
代码:
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
Run Code Online (Sandbox Code Playgroud)
我不明白为什么会发生这个错误。当我测试第 8 行时
config.permutations = [[1] + x for x in config.permutations]
Run Code Online (Sandbox Code Playgroud)
在正常情况下,通过在 Shell 中列出一个列表,例如:
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])
Run Code Online (Sandbox Code Playgroud)
它有效,但是在方法中使用完全相同的代码时,我收到有关添加元组的错误... [1] 不是列表吗?
有人可以帮助我吗?
谢谢!
在您在 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),...]
Run Code Online (Sandbox Code Playgroud)
这解释了错误。
这样做:
config.permutations = [[1] + list(x) for x in config.permutations]
Run Code Online (Sandbox Code Playgroud)
解决了这个问题。