Python 如何创建两个值的序列?
我有一个不同组合的列表,即:Python 如何创建两个值的序列?,python,Python,我有一个不同组合的列表,即: list1 = [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)] 我还有另一个列表,在我的例子中,它看起来像: list2 = [1,1] 我想做的是取list2的两个值,将它们组合为(1,1),并将它们与list1中的元素进行比较,然后返回索引。我当前的尝试如下所示: def return_index(comb): try: return
list1 = [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
我还有另一个列表,在我的例子中,它看起来像:
list2 = [1,1]
我想做的是取list2
的两个值,将它们组合为(1,1)
,并将它们与list1
中的元素进行比较,然后返回索引。我当前的尝试如下所示:
def return_index(comb):
try:
return comb_leaves.index(comb)
except ValueError:
print("no such value")
不幸的是,它找不到它,因为它不是序列。有谁知道如何解决这个问题吗?你把“序列”和“元组”搞混了。列表和元组都是序列。非正式地说,序列是指任何具有长度且支持直接索引的内容,并且是可编辑的。例如,范围
对象也被视为序列
要从任何其他序列创建两元素元组,请使用构造函数:
test_element = tuple(list_2)
将给出:
list1: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2), (1, 1)]
index: 4
不确定无条件添加tup2
是否是您想要的
如果第二个列表在列表1中,您可能需要索引:
list1 = [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]list2 = [1,1]
tup2 = tuple(list2)
if tup2 in list1:
print('index:', list1.index(tup2))
else:
print('not found')
这就产生了:
index: 4
index
函数返回匹配的第一个元素。尝试以下操作:
list1 = [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
list2 = [1, 1]
def return_index(comb):
try:
return list1.index(tuple(comb))
except ValueError:
print("Item not found")
print(return_index(list2)) # 4
这一行:
list1.index(tuple(list2))
将
列表2
从列表转换为元组
list1
的元素是元组,因此要进行比较,list2
需要是一个tuple
<代码>元组(列表2)
将[1,1]
转换为(1,1)
(与列表1的元素类型相同)。错误是什么,什么不是序列?将列表2转换为元组,然后使用索引,元组(列表2)
列表1。索引(元组(列表2))
?请求原谅比请求允许更容易<代码>尝试-,但最好是
。
list1 = [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
list2 = [1, 1]
def return_index(comb):
try:
return list1.index(tuple(comb))
except ValueError:
print("Item not found")
print(return_index(list2)) # 4
list1.index(tuple(list2))