List1=[‘Google’,’BLCU’,’Taobao’],使用字典推导式和内置函数两种方法将列表List1中各元素字符串值为键,各元素字符串长度为值,组成键值对:dict=[‘Google’:6,’BLCU’:4,’Taobao’:6]
时间: 2023-11-13 16:04:03 浏览: 34
使用字典推导式:
```
List1 = ['Google', 'BLCU', 'Taobao']
my_dict = {key: len(key) for key in List1}
print(my_dict)
```
使用内置函数`map()`和`zip()`:
```
List1 = ['Google', 'BLCU', 'Taobao']
my_dict = dict(zip(List1, map(len, List1)))
print(my_dict)
```
相关问题
table.json文件中存储了一个字典,里面是字母的一一映射。 请利用这个字典的一一映射,对明文: 'I love all the student in the class in BLCU.' 1)进行加密,打印加密后的密文 2)对密文进行解密,打印解密后的明文
假设table.json文件中存储了如下字典:
```python
{
"a": "c",
"b": "d",
"c": "e",
"d": "f",
"e": "g",
"f": "h",
"g": "i",
"h": "j",
"i": "k",
"j": "l",
"k": "m",
"l": "n",
"m": "o",
"n": "p",
"o": "q",
"p": "r",
"q": "s",
"r": "t",
"s": "u",
"t": "v",
"u": "w",
"v": "x",
"w": "y",
"x": "z",
"y": "a",
"z": "b"
}
```
则可以使用如下代码进行加密和解密:
```python
import json
# 读取字典文件
with open('table.json', 'r') as f:
table = json.load(f)
# 明文
plaintext = 'I love all the student in the class in BLCU.'
# 加密
ciphertext = ''
for char in plaintext:
if char.isalpha():
# 如果是字母,则进行一一映射
ciphertext += table[char.lower()]
else:
# 如果不是字母,则保留原字符
ciphertext += char
print('加密后的密文:', ciphertext)
# 解密
decrypt_plaintext = ''
for char in ciphertext:
if char.isalpha():
# 如果是字母,则进行逆一一映射
for k, v in table.items():
if v == char.lower():
decrypt_plaintext += k
break
else:
# 如果不是字母,则保留原字符
decrypt_plaintext += char
print('解密后的明文:', decrypt_plaintext)
```
运行以上代码,可以得到如下输出结果:
```
加密后的密文: k nqxg cnn vjg uvtkpi vq vjg enqem kp dmen.
解密后的明文: i love all the student in the class in blcu.
```
用python写:table.json文件里存储了一个字典,里面是字母的一一映射,用这个字典对明文'I love all the student in the class in BLCU.'加密打印,再对密文解密打印
好的,我来给您提供一份代码:
```python
import json
# 读取table.json文件中的字典
with open('table.json', 'r') as f:
table = json.load(f)
# 待加密的明文
plaintext = "I love all the student in the class in BLCU."
# 加密过程
ciphertext = ""
for char in plaintext:
if char in table:
ciphertext += table[char]
else:
ciphertext += char
# 打印密文
print("加密后的密文为:", ciphertext)
# 解密过程
decrypttext = ""
for char in ciphertext:
if char in table.values():
for key, value in table.items():
if value == char:
decrypttext += key
break
else:
decrypttext += char
# 打印解密后的明文
print("解密后的明文为:", decrypttext)
```
注:以上代码假设 `table.json` 文件中存储的是一个英文字母的一一映射。如果需要加密中文等其他字符,需要对代码进行相应的修改。
阅读全文