【问题标题】:Inserting items in a list with python while looping循环时使用python在列表中插入项目
【发布时间】:2022-12-16 23:21:03
【问题描述】:

我正在尝试更改以下代码以获得以下回报:

“1 2 3 ... 31 32 33 34 35 36 37 ... 63 64 65”

def createFooter2(current_page, total_pages, boundaries, around) -> str:
    footer = []
    page = 1
    #Append lower boundaries
    while page <= boundaries:
        footer.append(page)
        page += 1
    #Append current page and arround
    page = current_page - around
    while page <= current_page + around:
        footer.append(page)
        page += 1
    #Append upper boundaries
    page = total_pages - boundaries + 1
    while page <= total_pages:
        footer.append(page)
        page += 1
    #Add Ellipsis if necessary
    for i in range(len(footer)):
        if i > 0 and footer[i] - footer[i - 1] > 1:
            footer.insert(i, "...")
    result = ' '.join(str(page) for page in result)
    print(result)
    return result

createFooter2(34, 65, 3, 3)

如果下一页不紧挨着它,我想在页面之间插入一个“...”。但是我无法插入列表。

我应该如何更改代码以使其工作?

【问题讨论】:

  • 在我的脑海中,我首先列出了我必须添加'...'的索引,然后从较高的索引到较低的索引进行插入。

标签: python list insert


【解决方案1】:

正如我评论的那样,我首先记录所有不连续性索引,然后从高到低插入“...”(因为修改循环遍历的可迭代对象会导致问题):

a = list(range(50))
a.remove(6)
a.remove(23)
a.remove(45)

indexes = []
for i in range(1,len(a)):
    if a[i] != a[i-1]+1:
        indexes.append(i)

for i in indexes[::-1]:
    a.insert(i,'...')

a
# [0, 1, 2, 3, 4, 5, '...', 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, '...', 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, '...', 46, 47, 48, 49]

【讨论】:

    猜你喜欢
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    • 2015-12-25
    相关资源
    最近更新 更多