簡體   English   中英

'list' object 不能解釋為 integer 並且列表索引必須是整數或切片,而不是列表

[英]'list' object cannot be interpreted as an integer and list indices must be integers or slices, not list

我一直在研究一種涉及遺傳密碼的算法。 我首先將所有 4 個遺傳鹼基 A、C、T、G 與一個列表相關聯。 A 是 1,0,0,0。 C 為 0,1,0,0。 T 為 0,0,1,0,G 為 0,0,0,1。 有兩種不同的遺傳密碼,一種是原始密碼,另一種是基因突變的密碼。 該算法將根據兩個遺傳密碼之間的差異得出給出的數據的結論。 但首先,我需要對數據進行某種預處理,然后才能對算法做出結論。

This part of the code should essentially go through both the original code and the new code, compare them position by position, and determine if that position is equal. 如果您查看下面的代碼,例如,position 0 中的 A 和 A 是相等的。 但是, position 1 有 T 和 C 所以它不相等。 for 循環旨在循環遍歷列表的兩個部分。

代碼如下所示:

# Assigning all 4 base letters to a certain list of numbers so it can be edited later based on what the new genetic code has.
A = [1,0,0,0]
C = [0,1,0,0]
T = [0,0,1,0]
G = [0,0,0,1]

# Making two sample pieces of genetic code

original = [A,T,C,G,T,A,G]
copy = [A,C,C,A,T,G,G]

# Going through both the new and original list and comparing values at every position(0-6)

for i in range(original):
    if original[i] == copy[i]:
      print("They're the same")
    else:
      print("They're not the same.")
    i += 1 

我得到的錯誤是“列表”object 不能被解釋為 integer。 我在堆棧溢出中讀到我應該刪除 for 語句的范圍部分。 我嘗試了不同的變體並得到“列表索引必須是整數或切片,而不是列表。” 在閱讀有關此錯誤的更多帖子后,人們說要添加范圍。 所以它來回走動。

有誰知道如果我合並范圍,為什么會出現這兩個錯誤? 我沒有遺漏算法的另一部分。 我對 python 比較陌生,所以我可能會遺漏一些非常簡單的東西。

將您的 for 循環更改為:

for i,v in enumerate(original):
    if v == copy[i]:
      print("They're the same")
    else:
      print("They're not the same.")

enumerate()將接收一個數組,並返回一個生成器,該生成器在每次迭代期間對齊數組的索引和值。

或者,您可以使用zip()

for a,b in zip(original,copy):
    if a == b:
      print("They're the same")
    else:
      print("They're not the same.")

該線程中的另一個答案工作正常。 作為替代方案,您可以zip兩個列表,然后同時比較它們。 不需要索引。

for o,c in zip(original, copy):
    if o == c:
      print("They're the same")
    else:
      print("They're not the same.")

要使用您現有的代碼: range需要一個integer值,您提供一個list ,將其更改為 original 的長度,而不是 for 循環自動遞增i - 不要在循環結束時自行遞增

for i in range(len(original)):
    if original[i] == copy[i]:
      print("They're the same")
    else:
      print("They're not the same.")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM