例如,“拯救我們的靈魂”訊息將被加密為:“Sv u oliaeorSu”,然后我想將“Sv u oliaeorSu”解密為其原始內容。我已經執行了加密,但解密看起來很困難。最后我想將兩個串列的專案連接成一個新的專案。
例如 lst1=[a,c,e,g]
lst2=[b,d,f]
我想要的清單是 lst3=[a,b,c,d,e,f,g]
str1=input("Enter the String ??")
mystr=""
list1=[]
list2=[]
for i in range(len(str1)):
if i%2==0:
list1.append(str1[i])
else:
list2.append(str1[i])
list1.append("i")
encrypted="".join(map(str,list1 list2))
print("Encryption :",encrypted)
# (b) Decryption
list3=[];list4=[]
dec1=[];dec2=[]
length=len(list1 list2)
for i in range(length):
list3.append(encrypted[i])
else:
list4.append(encrypted[i])
if "i" in (list3):
list3.pop(list3.index("i"))
print(*list3)
len1=len(list3)
if len1%2==0:
for i in range(len1//2):
dec1.append(list3[i])
dec2.append(list3[i len1//2])
print(dec1)
print(dec2)
decX=[]
i=0
while(i<len(dec1)):
print(dec1[i],end="")
print(dec2[i],end="")
i =1
else:
for i in range(len1//2 1):
dec1.append(list3[i])
dec2.append(list3[i len1//2])
if len1%2!=0:
dec2.pop(0)
print(dec1)
print(dec2)
i=0
while(i<len(dec1)):
print(dec1[i],end="")
if len(dec2) != len(dec1):
i =1
print(dec2[i-1],end="")
i =1
i-=1
輸出
Enter the String ??1234567
Traceback (most recent call last):
File "C:/Users/SHUBHAM/PycharmProjects/Hello World/Basic Programs/Ass 4.py", line 460, in <module>
Encryption : 1357i246
1 3 5 7 2 4 6
['1', '3', '5', '7']
['2', '4', '6']
1234567 print(dec2[i-1],end="")
IndexError: list index out of range
Process finished with exit code 1
uj5u.com熱心網友回復:
您可以使用 zip() 方法。然后使用串列理解將串列展平。
lst1 = ['a','c','e','g']
lst2 = ['b','d','f']
def merge(lst1, lst2):
lst3 = list(zip(lst1, lst2))
lst3 = [l for y in lst3 for l in y]
extra = None
if len(lst1) > len(lst2):
lst3.append(lst1[-1])
elif len(lst1) < len(lst2):
lst3.append(lst1[-2])
return lst3
merge_list = merge(lst1,lst2)
print(merge_list)
uj5u.com熱心網友回復:
您可以使用itertools.zip_longest:
from itertools import zip_longest
def encrypt(s):
odd = s[::2]
even = s[1::2]
return odd even
def decrypt(s):
odd = s[:(len(s) 1)//2]
even = s[(len(s) 1)//2:]
lst = [x y for x, y in zip_longest(odd, even, fillvalue='')]
return(''.join(lst))
s = "Save our Soul"
print(encrypt(s)) # Sv u olaeorSu
print(decrypt(encrypt(s))) # Save our Soul
如果您zip_longest出于某種原因不想使用,那么您可以使用zip但需要注意oddwhen的最后一個元素odd長于even:
def decrypt(s):
odd = s[:(len(s) 1)//2]
even = s[(len(s) 1)//2:]
lst = [x y for x, y in zip(odd, even)]
if len(odd) > len(even):
lst.append(odd[-1])
return(''.join(lst))
uj5u.com熱心網友回復:
您可以執行以下操作來獲取 final_list
def merge_list(lst1, lst2):
lst3 = []
while lst1 and lst2:
lst3.append(lst1.pop(0))
lst3.append(lst2.pop(0))
if lst1:
lst3.extend(lst1)
if lst2:
lst3.extend(lst2)
return lst3
lst1 = ['a', 'c', 'e', 'g']
lst2 = ['b', 'd', 'f']
print(merge_list(lst1, lst2))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/394052.html
