3 个评论
你所要求的没有使用 str ,但你的代码却使用了它。
是的,我想知道如何做到不使用 str
你想做的操作不是 "连接"--那会给你一个类似 1234567 的结果。 你所做的是将两个数字交错排列。
python
python-3.x
integer
user15033416
user15033416
发布于 2021-01-19
3 个回答
Samwise
Samwise
发布于 2021-01-19
已采纳
0 人赞同

用f弦代替 str ,用 zip_longest 来组合两个弦。

>>> from itertools import zip_longest
>>> int(''.join((x or "") + (y or "") for x, y in zip_longest(f"{a}", f"{b}")))
1425367

如果你有一些 "不进口 "的规则,用内置的zip来做这件事也不会太难,但你需要对后面的数字进行特殊处理。

>>> int(''.join((x or "") + (y or "") for x, y in zip(f"{a}", f"{b}")) + f"{a}")[len(f"{b}"):] + f"{b}"[len(f"{a}"):]
1425367
    
仍然是一个str类型,需要一个int类型。
啊,不清楚OP希望这个实际的类型是什么 -- 如果它应该是一个 int 在最后,用 int 包裹整个东西,你还是没有使用 str 运算符。
要转换为int的最终结果
如果你想在不涉及任何字符串转换的情况下做到这一点,你可以通过编写一个函数将字符串分解成一个数字列表,然后再编写一个函数将该列表重新组合成一个单一的int。 这实际上只是重写了字符串/数字的转换函数,所以并不像它有多大效率。
Akshay Sehgal
Akshay Sehgal
发布于 2021-01-19
0 人赞同

试试这种方法,没有任何形式的 string fstrings 。纯粹的数字方法 -

from itertools import zip_longest
def get_pos_nums(num):
    pos_nums = []
    while num != 0:
        pos_nums.append((num % 10))
        num = num // 10
    return list(reversed(pos_nums))
zipped = zip_longest(get_pos_nums(a), get_pos_nums(b))
digits = [i for j in zipped for i in j if i!=None]
number = sum(d * 10**i for i, d in enumerate(digits[::-1]))
1425367
  • The first function breaks a number into its digits by dividing by 10
  • Next zip_longest zips the 2 lists in the order provided, giving None if one of the strings runs out of digits.
  • Flatten this list of digits and remove the Nones
  • Combine them with a sum after multiplying each with power of 10s
  • OP要求答案是 1425367 ,所以他们实际上并不希望数字被串联起来,而是交错排列。
    你能不能详细介绍一下这个解决方案?有什么方法可以不使用numpy而做到这一点吗?我还希望它们是 "交错 "的,而不仅仅是彼此相邻的。
    @lolnoname,刚刚在进行修复。我以为你想把a和b相加,而不是把它们压缩。
    Moinuddin Quadri
    Moinuddin Quadri
    发布于 2021-01-19
    0 人赞同

    下面是我实现这一目标的方法,无需使用字符串(或 f-string ):

  • Create a function to split your numbers into list of integers
  • Merge list of both the integers containing corresponding numbers together
  • Join the numbers in the list using multiplication by 10 to get desired final number
  • Step 1: Split number to list of integers

    使用 math.log10() 创建了自定义函数,从给定的字符串中返回整数列表。

    from math import log10
    def get_num_left_to_right(num):
        n = int(log10(num))
        for i in range(n, -1, -1):
            fac = 10**i
            x = num//fac
            yield x
            num -= x * fac
    

    抽样运行。

    a, b = 123, 4567
    x = list(get_num_left_to_right(a))
    # where `x` holds:
    # [1, 2, 3]
    y = list(get_num_left_to_right(b))
    # where `y` holds:
    # [4, 5, 6, 7]
    

    Step 2: Merge both the lists with corresponding number together

    我正在使用itertools.chainitertools.izip_longest以及list comprehension来实现这一目标。比如说。

    from itertools import izip_longest, chain
    num_list = [x for x in chain(*izip_longest(x, y)) if x is not None]
    # where `num_list` will hold:
    # [1, 4, 2, 5, 3, 6, 7]
    

    Step 3: Multiply the number in list by the power of 10

    最后,我将列表中的数字乘以10**(length-i-1),得到最终数字中所需要的整数位置。

    num, length = 0, len(num_list)
    for i, n in enumerate(num_list):