[英]How to create a sequence of two values?
I have a list with different combinations, ie: 我有一个具有不同组合的列表,即:
list1 = [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
I also have another list, in my case one looking like: 我也有另一个列表,在我的情况下看起来像:
list2 = [1,1]
What I would like to do is to take the two values of list2
, put them together as (1,1)
, and compare them with the elements in list1
, then returning the index. 我想做的是采用
list2
的两个值,将它们放在一起作为(1,1)
,并将它们与list1
的元素进行比较,然后返回索引。 My current attempt is looking like this: 我当前的尝试如下所示:
def return_index(comb):
try:
return comb_leaves.index(comb)
except ValueError:
print("no such value")
Unfortunately, it cant find it, because it's not a sequence. 不幸的是,它找不到序列,因为它不是序列。 Anyone with any good idea of how to fix this?
任何有解决此问题的好主意的人吗?
You are confusing "sequence" with "tuple". 您正在将“序列”与“元组”混淆。 Lists and tuples are both sequences.
列表和元组都是序列。 Informally, a sequence is anything that has a length and supports direct indexing in addition to being iterable.
非正式地,序列是任何具有长度的东西,除了可迭代之外,还支持直接索引。 A
range
object is considered to be a sequence too for example. 例如,
range
对象也被认为是一个序列。
To create a two element tuple from any other sequence, use the constructor: 要从任何其他序列创建两个元素元组,请使用构造函数:
test_element = tuple(list_2)
list3 = tuple(list2)
print(list3 in list1) #Check if it exists.
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)
list1.append(tup2)
print('list1:',list1)
print('index:', list1.index(tup2))
will give this: 将给出以下内容:
list1: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2), (1, 1)]
index: 4
Not sure if unconditionally adding tup2
is what you want. 不知道您是否想要无条件添加
tup2
。
Maybe you ask for the index, if the 2nd list is in list1: 如果第二个列表在list1中,则可能需要索引:
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')
That gives: 这给出了:
index: 4
the index
function returns the first element that matches. index
函数返回匹配的第一个元素。
Try this: 尝试这个:
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
With this line: 用这行:
list1.index(tuple(list2))
Convert list2
into a tuple
from a list
. 将
list2
从list
转换为tuple
。 list1
's elements are tuples, so to make the comparison, list2
needs to be a tuple
. list1
的元素是元组,因此要进行比较, list2
需要是一个tuple
。 tuple(list2)
turns [1, 1]
into (1, 1)
(the same type as the elements of list1
). tuple(list2)
将[1, 1]
变成(1, 1)
(与list1
的元素相同的类型)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.