yjptx121 发表于 2020-3-16 20:40:10

关于__sub__运算的问题

我想用一个笨办法去计算字符串的相减,但是结果却没有达到预期,想知道原因,请教各位资深大佬,附代码:
class Nstr(str):
    def __sub__(self, other):
      a = list(self)
      c = str()
      count = 0
      num = a.count('i')
      print('总共有{}处相同'.format(num))
      for each_other in a:
            if each_other == other:
                count += 1
                a.remove(each_other)
                print('第{}次删除!a => {}'.format(count, a))
      for each_a in a:
            c += each_a
      return c

a = Nstr('I love FishC. com!iiiiiiii')
b = Nstr('i')
print(a - b)

运行后结果如图:
总共有9处相同
第1次删除!a => ['I', ' ', 'l', 'o', 'v', 'e', ' ', 'F', 's', 'h', 'C', '.', ' ', 'c', 'o', 'm', '!', 'i', 'i', 'i', 'i', 'i', 'i', 'i', 'i']
第2次删除!a => ['I', ' ', 'l', 'o', 'v', 'e', ' ', 'F', 's', 'h', 'C', '.', ' ', 'c', 'o', 'm', '!', 'i', 'i', 'i', 'i', 'i', 'i', 'i']
第3次删除!a => ['I', ' ', 'l', 'o', 'v', 'e', ' ', 'F', 's', 'h', 'C', '.', ' ', 'c', 'o', 'm', '!', 'i', 'i', 'i', 'i', 'i', 'i']
第4次删除!a => ['I', ' ', 'l', 'o', 'v', 'e', ' ', 'F', 's', 'h', 'C', '.', ' ', 'c', 'o', 'm', '!', 'i', 'i', 'i', 'i', 'i']
第5次删除!a => ['I', ' ', 'l', 'o', 'v', 'e', ' ', 'F', 's', 'h', 'C', '.', ' ', 'c', 'o', 'm', '!', 'i', 'i', 'i', 'i']
运行后的结果为:I love FshC. com!iiii

zltzlt 发表于 2020-3-17 13:10:02

看这里:https://fishc.com.cn/thread-158978-1-1.html

以下代码完美解决你的问题:

class Nstr(str):
    def __sub__(self, other):
      a = list(self)
      c = str()
      count = 0
      num = a.count('i')
      print('总共有{}处相同'.format(num))
      for each_other in a[:]:    # 修改
            if each_other == other:
                count += 1
                a.remove(each_other)
                print('第{}次删除!a => {}'.format(count, a))
      for each_a in a:
            c += each_a
      return c


a = Nstr('I love FishC. com!iiiiiiii')
b = Nstr('i')
print(a - b)

yjptx121 发表于 2020-3-17 22:05:14

zltzlt 发表于 2020-3-17 13:10
看这里:https://fishc.com.cn/thread-158978-1-1.html

以下代码完美解决你的问题:

多谢!

yjptx121 发表于 2020-3-17 22:18:15

本帖最后由 yjptx121 于 2020-3-17 22:21 编辑

我在网上搜索了一下列表副本,大概意思就是:分片只会复制当前序列的内容,不会复制序列内的数据结构,那就是即使remove了列表中的某个元素,但是整个列表的索引顺序还是维持原状不会改变
页: [1]
查看完整版本: 关于__sub__运算的问题