2016-12-15 40 views
-5

從這個評論:如何轉換INT(輸入)到列表

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: "))) 

編輯:python3兼容性變化得益於Tadhg麥當勞 - 延森

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")) 
+0

「將int轉換爲列表」究竟意味着什麼?你可以用'[a]'構造一個包含int的列表,但這不是一個轉換。 –

+0

我的意思是如果用戶輸入「00000000」是一個整數,它將變成[0,0,0,0,0,0,0,0] – vxguhe

+0

,如果他們輸入'147'會怎麼樣?該列表是否包含「[1,4,7]」? –

回答

2

我覺得這是你所需要的:

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

格式字符串"{:08b}"意味着:整數轉換爲字符串以二進制,至少8位,0填充。

+2

顯然地圖返回一個python3中的迭代 –

+1

這就是爲什麼我不再使用'map'的原因,我使用列表解析代替 –

+0

我不知道+1 – Jakub

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: "))) 

編輯:python3兼容性變化得益於Tadhg麥當勞 - 延森

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")) 
+0

要與python3兼容,你需要將你的'map' cal l調用'list'或使用列表理解。 –

+0

這工作。非常感謝!!! ❤️ – vxguhe

+0

我得到S = a^b#^是xor按位運算符 TypeError:^:'list'和'list'不受支持的操作數類型 – vxguhe