【问题标题】:Where can c(digit) be found in n(number) [closed]在 n(number) 中哪里可以找到 c(digit) [关闭]
【发布时间】:2022-01-15 23:36:38
【问题描述】:
n = int(input("Unesite n: "))
c = int(input("Unesite c: "))

def where(n, c):
    where = []
    for i in range(1, n + 1):
        dig = i
        while dig > 0:
            if dig % 10 == c:
                where.append(i)
                break
            dig //= 10
    print(where)

这个问题的答案可能很愚蠢,但是...:/ 对于输入 n=22 和 c=1,输出为 [1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21]。 我很好奇如何从输出、f 字符串或其他内容中删除 []? 我希望输出看起来像“从数字 1 到 {n},数字 {c} 以数字显示:{where(n, c)}。

【问题讨论】:

  • 欢迎来到 Stack Overflow。请阅读How to Ask。 “c”和“n”在没有上下文的情况下是没有意义的,所以你的标题对于描述你的问题不是很有帮助。这段代码应该做什么?你正在打印一个列表,所以是的,它会在它周围显示[]。这部分尝试打印诸如“从数字 1 到 {n},数字 {c} 以数字显示:{where(n, c)}”之类的内容?
  • 对我来说好像是作业...
  • 代码需要打印1到n(包括n)之间的数字,其中包含数字c。等等 n=22 和 c=1 输出是 [1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 21]。我很清楚我正在打印一份清单。我的问题是我可以编辑列表的外观,更具体地说,我可以从输出中删除 [] 吗?

标签: python for-loop while-loop


【解决方案1】:
def where(n, c):
    where = []
    for i in range(1, n + 1):
        dig = i
        while dig > 0:
            if dig % 10 == c:
                where.append(i)
                break
            dig //= 10
    for e in where:
        print(e, end= " ")

那么输出将是

1 10 11 12 13 14 15 16 17 18 19 21

【讨论】:

    【解决方案2】:

    这是另一个解决方案:

    def where(n, c):
     where = []
     for i in range(1, n + 1):
         dig = i
         while dig > 0:
             if dig % 10 == c:
                 where.append(i)
                 break
             dig //= 10
     print(str(where)[1:-1])
    
    
    n = 22
    c = 1
    where(n, c)
    

    【讨论】:

      猜你喜欢
      • 2011-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-13
      相关资源
      最近更新 更多