簡體   English   中英

如何使用python中的for循環計算列表中四個相鄰元素的數量?

[英]How to count the number of four adjecent elements in a list using for loops in python?

我有一個字母列表,我需要計算字母J出現為JJJJ(4 Js)的次數。 必須使用for循環(而不是.count)來完成。 我寫了一些代碼,但出現錯誤,表明索引超出范圍。 而且我知道代碼是不正確的,因為如果有JJJJJ(5 Js),那么我的代碼會將其計為2xJJJJ(4 Js),結果將是4而不是3。

我將不勝感激任何幫助或建議。 謝謝!

data = ["A","B","A","A","A","B","J","J","J","J","B","B","B","J","J","J","J","J","B","A","A","A","J","J","J","J",]
for t in range(len(data)):
    if t<len(data) and data[t] == "J":
        if t<len(data) and data[t+1] == "J":
            if t<len(data) and data[t+2] == "J":
                if data[t+3] == "J":
                        countTTT_1 += 1
print("JJJJ appears" ,countTTT_1)

您可以執行以下操作:

data = 'ANDJRJEJJJJARGJJJJCSEGJJJJJESFF'

def count_j(data: str, maxj: int) -> int:
    number_of_j = 0
    number_of_repetitions = 0

    for ch in data:
            if ch == 'J':
                n, number_of_j = divmod(number_of_j, maxj)

                number_of_repetitions += n
                number_of_j += 1

    n, _ = divmod(number_of_j, maxj)

    number_of_repetitions += n

    return number_of_repetitions

print(count_j(data, 4))

問題

在您的代碼中,您多次檢查t<len(data)但這並不能防止t+3大於len(data) - 1

只需進行很少的修改,您就可以編寫:

data = ["A","B","A","A","A","B","J","J","J","J","B","B","B","J","J","J","J","J","B","A","A","A","J","J","J","J",]
countTTT_1 = 0
for t in range(len(data)):
    if t<len(data) - 1 and data[t] == "J":
        if t<len(data) - 2 and data[t+1] == "J":
            if t<len(data) - 3 and data[t+2] == "J":
                if data[t+3] == "J":
                        countTTT_1 += 1
print("JJJJ appears" ,countTTT_1)
# ('JJJJ appears', 4)

您無需勾選t ,可以直接選擇正確的范圍:

data = ["A","B","A","A","A","B","J","J","J","J","B","B","B","J","J","J","J","J","B","A","A","A","J","J","J","J",]
countTTT_1 = 0
for t in range(len(data) - 3):
    if data[t] == "J":
        if data[t+1] == "J":
            if data[t+2] == "J":
                if data[t+3] == "J":
                        countTTT_1 += 1
print("JJJJ appears" ,countTTT_1)
# ('JJJJ appears', 4)

整個結構可以用sum器和切片代替sum

>>> s = 'ABAAABJJJJBBBJJJJJBAAAJJJJ'
>>> sum(1 for i in range(len(s) - 3) if s[i:i + 4] == 'JJJJ')
4

請注意,它像原始示例一樣計算重疊的子字符串。

如果不想計數重疊的子字符串,則可以在每次看到'J'字符時增加一個計數器。 計數器會因其他任何字符或達到“ 4”而復位。 在這種情況下, jjjj_counter會增加:

text = 'ABAAABJJJJBBBJJJJJBAAAJJJJ'

def count_jjjj(text):
  jjjj_counter = 0
  last_js = 0
  for char in text:
    if char == 'J':
      last_js += 1
      if last_js == 4:
        jjjj_counter += 1
        last_js = 0
    else:
      last_js = 0
  return jjjj_counter

print(count_jjjj(text))
# 3
print(count_jjjj('JJJ'))
# 0
print(count_jjjj('JJJJ'))
# 1
print(count_jjjj('JJJJJ'))
# 1
print(count_jjjj('JJ JJ'))
# 0

暫無
暫無

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

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