Python在Jupyter Notebook中:.append在每次运行时都会持续添加而不刷新列表

huangapple go评论57阅读模式
英文:

Python in Jupyter Notebook: .append kept adding without refresh the list in each run

问题

请帮助解决以下示例中在循环中使用append()时出现的奇怪行为。

我有一个字符串。

  1. 我从字符串中提取字母并将其存储在名为ltr的列表中。
  2. 我为ltr列表的每个元素指定条件。
  3. 我将布尔结果存储在名为ltr_spec的列表中。
  4. 如果我在Jupyter Notebook的另一个单元格中故意运行ltr_spec = []来初始化ltr_spec,则第一次运行时看起来很正常。
  5. 但是,如果我再次运行该单元格,ltr_spec会继续添加新元素,而不会像在代码开头定义的那样刷新为空列表。
  6. 请问这是循环、append()还是Jupyter Notebook的问题?

示例代码如下。

s = 'Qm1p4Q7p5d2'
ltr = []
# 测试“ltr”列表的每个元素是否满足字符串中字母的规格
ltr_j = False
ltr_spec = []

for i in s:
    if i.isalpha():
        ltr.append(i)
# 利用取模运算,一个数学概念,来定位字母的位置
if (len(ltr) % 3 == 0):
    for j in range(len(ltr)):
        # 测试ltr列表上的索引、字母和大小写规格
        if ((j % 3 == 0 and ltr[j] == "Q") or
            (j % 3 == 1 and ((ltr[j] == "d" and ltr[j+1] == "p") or (ltr[j] == "p" and ltr[j+1] == "d"))) or
            (j % 3 == 2 and ((ltr[j] == "d" and ltr[j-1] == "p") or (ltr[j] == "p" and ltr[j-1] == "d"))):
                ltr_j = True
        else:
            ltr_j = False
        ltr_spec.append(ltr_j)

第一次运行的输出:

ltr
['Q', 'm', 'p', 'Q', 'p', 'd']
ltr_spec
[True, False, False, True, True, True]

第二次运行的输出:

ltr
['Q', 'm', 'p', 'Q', 'p', 'd']
ltr_spec
[True, False, False, True, True, True, True, False, False, True, True, True]

第三次运行的输出:

ltr
['Q', 'm', 'p', 'Q', 'p', 'd']
ltr_spec
[True, False, False, True, True, True, True, False, False, True, True, True, True, False, False, True, True, True]
英文:

Please help with append() in a loop that behaves weird as shown below.

I have a string.

  1. I extract alphabet letters from the string and store to a list, called ltr.
  2. I specify the conditions for each element of the ltr list
  3. I stored the boolean result in a list, called ltr_spec
  4. It looks fine for the first run if I purposely run ltr_spec = [] in another cell of Jupyter Notebook to initialize ltr_spec.
  5. However, if I run the cell again, ltr_spec keep adding new elements without being refreshed as an empty list which was define at the beginning of the code.
  6. Note that the first append() in ltr.append() behaves as expected. But the second append() in ltr_spec.append() behaves unexpected when run the cell in Jupyter Notebook.

Would you please kindly tell me if it is the issue of the loop, or append(), or Jupyter Notebook?

Sample code below.

s ='Qm1p4Q7p5d2'
ltr = []
# Test if each element of 'ltr' satisfies the spec of alphabet letter in a string
ltr_j = False
ltr_spc = []

for i in s:
    if i.isalpha():
        ltr.append(i)
# Utilize the modulo operation, a math concept, to locate the position of the letters
if (len(ltr) % 3 == 0):
    for j in range(len(ltr)):
        # Test ltr list on the specs of index, letter, and upper/lower case
        if ((j % 3 == 0 and ltr[j] == "Q") or
                # Ask if there is a better way to write j %in% c(1,2) (R's match function) without using Numpy!
            (j % 3 == 1 and ((ltr[j] == "d" and ltr[j+1] == "p") or (ltr[j] == "p" and ltr[j+1] == "d"))) or
                # Ask if the following condition is redundant given the condition specified above is already checked..
            (j % 3 == 2 and ((ltr[j] == "d" and ltr[j-1] == "p") or (ltr[j] == "p" and ltr[j-1] == "d")))):
                ltr_j = True
        else:
            ltr_j = False
        ltr_spec.append(ltr_j)

Output in first run:

ltr
['Q', 'm', 'p', 'Q', 'p', 'd']
ltr_spec
[True, False, False, True, True, True]

Output in second run:

ltr
['Q', 'm', 'p', 'Q', 'p', 'd']
ltr_spec
[True, False, False, True, True, True, True, False, False, True, True, True]

Output in third run:

ltr
['Q', 'm', 'p', 'Q', 'p', 'd']
ltr_spec
[True,
 False,
 False,
 True,
 True,
 True,
 True,
 False,
 False,
 True,
 True,
 True,
 True,
 False,
 False,
 True,
 True,
 True]

答案1

得分: 1

你已经定义了ltr_spc = [],但在底部你调用了ltr_spec.append(ltr_j),所以列表没有被清空。

这里是在将ltr_spc = []更正为ltr_spec = []后的代码,重新运行多次后它会给出一致的输出。

英文:

You have defined ltr_spc = [] but at the bottom you call ltr_spec.append(ltr_j), so the list is not emptied.

Here is the code after correct ltr_spc = [] to ltr_spec = [], and it gives consistent output after re-run many times.

huangapple
  • 本文由 发表于 2023年2月19日 05:44:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75496578.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定