python - 在不使用任何预定义的 Python 函数的情况下在列表中查找运行

标签 python list python-3.x

我试图在不使用 Python 中预定义的列表函数(例如枚举、zip、索引等)的情况下在列表中查找运行。

通过运行,我的意思是给定一个列表 [1,2,3,6,4],我想返回一个新列表 [1,2,3] 以及返回运行开始和结束的位置,并且运行的长度。

下面是我对此的尝试,但我似乎无法理解,我似乎总是遇到索引超出范围错误的问题。

def run_cards (hand_shuffle, hand_sample):

    true_length = len(hand_shuffle) - 1
    y = 0
    r = []
    for x in range(len(hand_shuffle)):
        y = x + 1

        if y <= true_length: #Checks if y is in range with x 
            t = hand_shuffle[y] - hand_shuffle[x] #Subtracts the two numbers to see if they run
            r.append(t)

    lent = len(hand_shuffle)

    if hand_shuffle[lent-1] - hand_shuffle[lent-2] == 1:
        r.append(1)
    h = []

    for i in range(len(r)):

        if r[i] == 1: #If t from above for loop is equal to 1 append it to the new list
            h.append(i)
            h.append(i+1)

    p = []

    for j in h:
        p.append(hand_shuffle[j])

    print (p) 
    return hand_shuffle, hand_sample

现在,我的代码可以运行,但没有提供我正在寻找的东西。

最佳答案

>>> runFind(L)
[(4, 0), (2, 3), (2, 4)]
>>> def runFind(L):
...   i = 1
...   start = 0
...   answer = []
...   while i < len(L):
...     if L[i] != L[i-1]+1:
...       answer.append((i-start, start))
...       start = i
...     i += 1
...   answer.append((i-start, start))
...   
...   return answer
... 
>>> L = [1,2,3,6,4]
>>> runFind(L)
[(3, 0), (1, 3), (1, 4)]
>>> L = [0, 0, 0, 4, 5, 6]
>>> runFind(L)
[(1, 0), (1, 1), (1, 2), (3, 3)]
>>> L = [4, 5, 5, 1, 8, 3, 1, 6, 2, 7]
>>> runFind(L)
[(2, 0), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9)]
>>> L = [1, 1, 1, 2, 3, 5, 1, 1]
>>> runFind(L)
[(1, 0), (1, 1), (3, 2), (1, 5), (1, 6), (1, 7)]
>>> L = [1, 1, 1, 1]
>>> runFind(L)
[(1, 0), (1, 1), (1, 2), (1, 3)]
>>> L = [1, 2, 5, 6, 7]
>>> runFind(L)
[(2, 0), (3, 2)]
>>> L = [1, 0, -1, -2, -1, 0, 0]
>>> runFind(L)
[(1, 0), (1, 1), (1, 2), (3, 3), (1, 6)]

关于python - 在不使用任何预定义的 Python 函数的情况下在列表中查找运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19985560/

相关文章:

javascript - 填充数据列表中选项的更好方法

python - 从另一个站点调用 URL 到 Django 开发的站点

python - 如何有效地在具有不同维度的多维 numpy 数组中添加列?

R:如何将表格 reshape 为向量

python - 'import nltk' 上的“ModuleNotFoundError : No module named nltk. 指标”

python - 使用不同的结果对从 1st .. 开始的记录进行排名

python - 如何将 Tweepy OAuth 用于 Twitter 的新 API?

python - 在 python 中将列表转换为嵌套列表

java - 获取List中元素的类型

python - 如何管理多层字典,自定义列,减去列数据,添加新列?