【问题标题】:Looping a variable cyclically [closed]循环循环变量[关闭]
【发布时间】:2020-09-10 00:57:19
【问题描述】:

我有两个整数值,一个的位数明显少于另一个。例如:

x = 100
y = 1298411291836199301    (19 digits)

在 Python 中编码它的方法是什么,以便 x 通过循环它具有相同的位数,所以我想要类似的东西:

x =  1001001001001001001   (19 digits)

【问题讨论】:

  • 欢迎来到 SO,你有什么想要展示的吗?
  • 嗨,cobraclaire,你能告诉我们你到目前为止做了什么吗?这将使获得高质量帮助变得更加容易。

标签: python loops


【解决方案1】:

由于整数的位数只是其表示方式的副产品(以 10 为底),因此您必须将其转换为字符串。

x = 100
y = 1298411291836199301

x = str(x)
target_len = len(str(y))

while len(x) < target_len:
  x += x

# Cut off the last loop if it goes over the
# desired length, and turn it back into an int
x = int(x[:target_len])

# >>> x
# 1001001001001001001

【讨论】:

    【解决方案2】:

    你可以使用

    x = 100
    y = 1298411291836199301
    
    n = len(str(y))
    x = str(x)
    m = len(x)
    multiplier = n // m + 1
    
    x = ''.join( # join an iterable of strings into a single string
        (x for _ in range(multiplier)) # generator expression that returns x multiple times
        )[:n] # truncate the final string to the exact desired length
    x = int(x)
    
    print(x)
    print(y)
    

    输出

    1001001001001001001
    1298411291836199301
    

    【讨论】:

      猜你喜欢
      • 2015-07-18
      • 2012-03-26
      • 2023-03-28
      • 2016-08-15
      • 1970-01-01
      • 1970-01-01
      • 2021-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多