[英]Having trouble comparing lists and lists of list
I have a list of ints and a list of lists.我有一个整数列表和一个列表列表。 I need to compare the two.
我需要比较两者。
The list of lists has a name, and a set of ints.列表列表有一个名称和一组整数。 My list just has a set of ints.
我的列表只有一组整数。
I know that in python you can just say is list == list
.我知道在 python 你可以说
is list == list
。 However, the order the ints are in is import and in my list of lists I also have a name before the ints.但是,整数的顺序是导入的,在我的列表列表中,整数之前还有一个名称。
Example my list will be 4 1 6
while a list I need to compare it to will be bob 6 7 2
.例如,我的列表将是
4 1 6
而我需要与之比较的列表将是bob 6 7 2
。 I just need to compare the ints and if i compare 4 1 6
to 1 6 4
or 1 4 6
it would not compare.我只需要比较整数,如果我将
4 1 6
与1 6 4
或1 4 6
进行比较,则不会进行比较。
I've tried using loops but am not getting the result I want.我试过使用循环,但没有得到我想要的结果。
chdnalist
will be one list just a set of 3 ints. chdnalist
将是一个列表,只有一组 3 个整数。 dnalist
is a list of lists and one list will be bob, 4, 1, 3
the next will be alice 9, 6, 4
. dnalist
是一个列表列表,一个列表是bob, 4, 1, 3
下一个是alice 9, 6, 4
。
I need to compare the three ints from chdnalist
to the three ints in dna
list and print the name if it matches including order.我需要将
chdnalist
中的三个整数与dna
列表中的三个整数进行比较,如果匹配,则打印名称,包括顺序。
Here is the set of loops I was trying.这是我正在尝试的一组循环。 Currently the s loop doesn't increment.
目前 s 循环不会增加。
def compare(dnalist, chdnalist):
for i in range(1, len(dnalist)):
for s in range(1, len(dnalist[1])):
print (s)
if (chdnalist[i - 1] != dnalist[i][s]):
break
if (s == len(dnalist[1])):
print (dnalist[i][0])
return
else:
print ("No Match")
return
This is a copy of the csv file that becomes my list of lists (dnalist).这是 csv 文件的副本,它成为我的列表 (dnalist)。
name,AGATC,AATG,TATC
Alice,2,8,3
Bob,4,1,5
Charlie,3,2,5
I happen to know that the text file I use to create the list I compare it to when it has been translated turns into 4,1,5
(chdnalist).我碰巧知道我用来创建列表的文本文件,当它被翻译时,我将它与它进行比较变成了
4,1,5
(chdnalist)。 However, when I go to compare them the s loop doesn't iterate.但是,当我 go 比较它们时,s 循环不会迭代。 It only runs once.
它只运行一次。
Use spread assignment to split the name from the ints when iterating over dnalist
.迭代
dnalist
时,使用扩展分配将名称与整数分开。 Then you can use ==
to compare the list of ints.然后你可以使用
==
来比较整数列表。
Also, No match
should only be printed at the end of the loop, not during each iteration, since there could be a later match.此外,
No match
应该只在循环结束时打印,而不是在每次迭代期间打印,因为以后可能会有匹配。
Since you read dnalist
from a CSV file, everything will be read as strings, not integers.由于您从 CSV 文件中读取
dnalist
,因此所有内容都将被读取为字符串,而不是整数。 You'll need to convert them to integers before comparing.在比较之前,您需要将它们转换为整数。
def compare(dnalist, chdnalist):
for name, *dna in dnalist:
dna = list(map(int, dna))
if dna == chdnalist:
print(name)
return
print("No match")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.