如何更改列表的视图?

2024-06-28 15:16:46 发布

您现在位置:Python中文网/ 问答频道 /正文

晚上好!我有以下代码,当你写 python新建.py-命令提示符下的s13-p5。你知道吗

命令提示符打印的是: [[1, [0], [0]], [1, [0], [0]], [1, [0], [0]], [1, [0]], [1, [0]]]

但我想: [[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0], [1, 0]]

我该怎么做?你知道吗

-s12是字符串的长度,-p7是1

谢谢你!你知道吗

我的代码示例:

import argparse


p = argparse.ArgumentParser()
p.add_argument("-pulses", help = "number of pulses", type = int)
p.add_argument("-slots", help = "length of the rythm", type = int)
args = p.parse_args()
slots = args.slots
pulses = args.pulses


pauses = slots - pulses

mod = slots % pulses

rhythm = []

if mod != 0:
    i = 0
    j = 0
    temp = []

    while i < pulses:
        rhythm.append([1])
        i = i + 1

    while j < pauses:
        rhythm.append([0])
        j = j + 1

    m = slots
    n = pauses

    while (rhythm[-1]==[0]):

        if (n!=0):
            step = m%n
            hlp = n
            m = n
            n = step

            i = 0

            while (i<step):
                rhythm[i].append(rhythm[-1])
                rhythm.remove(rhythm[-1])
                i = i + 1

print (rhythm)

Tags: of代码addstepargparsehelpargsargument
3条回答

问题是这条线

rhythm[i].append(rhythm[-1])

rhythm[-1]返回一个列表([0][1])。所以你必须用extend而不是append。你知道吗

rhythm[i].extend(rhythm[-1])

Python List

晕眩的编码器肯定正确地回答了这个问题。 更一般地说,关于列表的附加和扩展:

  • 目的地_列表.append(附加项)将项附加到列表中。如果附加项是列表,则此列表将按原样附加,并成为目标列表末尾的附加项。

  • 目的地_列表.扩展(列表扩展名)用另一个列表扩展一个列表,该列表的每一项都被单独附加到目标列表的末尾。

注意:这只是对评论的复制和粘贴。你知道吗

签出this。你知道吗

我还没有完全分析你的代码,但我相信你的问题出在append()。尝试将其替换为extend()。你知道吗

相关问题 更多 >