如何将int(input)转换为lis

2024-04-20 04:54:43 发布

您现在位置:Python中文网/ 问答频道 /正文

从这条评论中:

I mean if the user inputs "00000000" which is an integer, it will become [0,0,0,0,0,0,0,0]

我相信你想要的是:

a = list(map(int, input("enter first byte: ")))
b = list(map(int, input("enter second byte: ")))

编辑:由于Tadhg-McDonald-Jensen,python3兼容性发生了变化

edit2:由于不能在列表中使用“^”,因此可以改为使用以下代码:

a = input("enter first byte: ")
b = input("enter second byte: ")

def half_adder(a, b):
    S = ""
    c = ""
    for i in range(8):
        S += str(int(a[i]) ^ int(b[i]))
        c += str(int(a[i]) & int(b[i]))
    return (S,c)

def full_adder(a, b, c):
    (s1, c1) = half_adder(a, b)
    (s2, c2) = half_adder(s1, c)
    return (s2, (c1 or c2))

print(full_adder(a, b, "00000000"))

Tags: mapinputreturndefbytefulllistint
2条回答

我想这就是你需要的:

>>> x=42
>>> list(map(int, "{:08b}".format(x)))
[0, 0, 1, 0, 1, 0, 1, 0]

格式字符串"{:08b}"表示:将整数转换为二进制字符串,至少8位,0填充。你知道吗

从这条评论中:

I mean if the user inputs "00000000" which is an integer, it will become [0,0,0,0,0,0,0,0]

我相信你想要的是:

a = list(map(int, input("enter first byte: ")))
b = list(map(int, input("enter second byte: ")))

编辑:由于Tadhg-McDonald-Jensen,python3兼容性发生了变化

edit2:由于不能在列表中使用“^”,因此可以改为使用以下代码:

a = input("enter first byte: ")
b = input("enter second byte: ")

def half_adder(a, b):
    S = ""
    c = ""
    for i in range(8):
        S += str(int(a[i]) ^ int(b[i]))
        c += str(int(a[i]) & int(b[i]))
    return (S,c)

def full_adder(a, b, c):
    (s1, c1) = half_adder(a, b)
    (s2, c2) = half_adder(s1, c)
    return (s2, (c1 or c2))

print(full_adder(a, b, "00000000"))

相关问题 更多 >