一.字符串
1.字符串转为列表
list()方法
a = "fdfjnjklsdfn"
print(list(a))
输出结果为:['f', 'd', 'f', 'j', 'n', 'j', 'k', 'l', 's', 'd', 'f', 'n']
按特定分隔符拆分
a = "apple.banana.orange"
print(a.split("."))
输出结果为:['apple', 'banana', 'orange']
二.列表
1.列表转为字符串
str()方法
list = ["hello","world","python"]
print(str(list))
输出结果为:['hello', 'world', 'python']
这里可以使用type()方法来验证数据类型
join()方法
list = ["hello","world","python"]
print(" ".join(list))
输出结果为:hello world python
使用这个方法前必须保证列表元素全部是字符串否则会报错
2.列表转为字典
dict()方法 适用于列表元素是键值对
list = [("name","alex"),("age",25),("sex","男")]
print(dict(list))
输出结果为:{'name': 'alex', 'age': 25, 'sex': '男'}
zip()+dict()方法 适用于把两个列表合为一个字典
list1 = ["name","age","sex"]
list2 = ["alex","25","男"]
print(dict(zip(list1, list2)))
输出结果为:{'name': 'alex', 'age': 25, 'sex': '男'}
需要生成新的键
list = ["张三",25,"男","成都"]
N_list = {i:list[i] for i in range(len(list))}
print(N_list)
输出结果为:{0: '张三', 1: 25, 2: '男', 3: '成都'}
3.列表去重
set()方法
list1 = [1,1,2,2,3,3,4,5]
print(set(list1))
输出结果为:{1, 2, 3, 4, 5}
fromkeys()方法
list1 = [1,1,2,2,3,3,4,5]
list2 ={}.fromkeys(list1).keys()
print(list2)
输出结果为:dict_keys([1, 2, 3, 4, 5])
这个方法会使得list2的数据类型不在是list类型
sort()方法
4.列表排序
reverse()
list1 = [8,6,5,2,9,4]
list1.reverse()
print(list1)
输出结果为:[4, 9, 2, 5, 6, 8]
将原列表倒序排列
sorted()
list1 = [8,6,5,2,9,4,]
print(sorted(list1))
输出结果为:[2, 4, 5, 6, 8, 9]
从小到大排列
倒序为:
list1 = [8,6,5,2,9,4,]
print(sorted(list1,reverse=True))
输出结果为:[9, 8, 6, 5, 4, 2]
从大到小排列
sort()
list1 = [8,6,5,2,9,4]
list1.sort()
print(list1)
输出结果为:[2, 4, 5, 6, 8, 9]
从小到大排列
三.字典
1.字典转为列表
将字典的键(keys)转为列表
dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print(list(dict.keys()))
输出结果为:['name', 'age', 'city']
将字典的值(values)转为列表
dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print(list(dict.values()))
输出结果为:['Alice', 25, 'New York']
将字典的键值对(items)转为列表
dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print(list(dict.items()))
输出结果为:[('name', 'Alice'), ('age', 25), ('city', 'New York')]
1万+

被折叠的 条评论
为什么被折叠?



