Python笔记:List相关操作
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python笔记:List相关操作,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2352字,纯文字阅读大概需要4分钟。
内容图文
![Python笔记:List相关操作](/upload/InfoBanner/zyjiaocheng/604/7fb711e6f8254c5f8fd9cce93f96a48b.jpg)
目录
List相关操作小例子
获取list的下标和值
>>> mylist = ['a', 'b', 'c', 'd']
>>> for index, value in enumerate(mylist):
... print(index, value)
...
0 a
1 b
2 c
3 d
>>>
删除list中的空字符
list1 = ['1', '','2', '3', ' ', ' 4 ', ' 5', ' ','6 ', '', ' ',None, '7']
print(list1)
list2 = list(filter(None, list1))
print(list2) # ['1', '2', '3', ' ', ' 4 ', ' 5', ' ', '6 ', ' ', '7']
list3 = [x.strip() for x in list2]
print(list3) # ['1', '2', '3', '', '4', '5', '', '6', '', '7']
list4 = list(filter(None, list3))
print(list4) # ['1', '2', '3', '4', '5', '6', '7']
删除list元素
使用remove、pop和del方法参删除list中的某个元素
>>> mylist = ['a', 'b', 'c', 'd','e','f','g','h']
>>> mylist.remove('a')
>>> mylist
['b', 'c', 'd', 'e', 'f', 'g', 'h']
>>> mylist.pop(0)
'b'
>>> mylist
['c', 'd', 'e', 'f', 'g', 'h']
>>> del mylist[0]
>>> mylist
['d', 'e', 'f', 'g', 'h']
>>> del mylist[0:2]
>>> mylist
['f', 'g', 'h']
>>> del mylist
>>> mylist
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'mylist' is not defined
>>>
计算中位数
def get_median(data):
data.sort()
half = len(data) // 2
return (data[half] + data[~half]) / 2
将字符串list转换为int
>>> test_list = ['1', '4', '3', '6', '7']
>>> test_list = list(map(int, test_list))
>>> test_list
[1, 4, 3, 6, 7]
>>>
合并、连接字符串list
>>> test_list = ['192', '168', '0', '1']
>>> test_list = '.'.join(test_list)
>>> test_list
'192.168.0.1'
>>>
取多个字符串/list交集
>>> a = ['123','234','1253']
>>> list(reduce(lambda x,y : set(x) & set(y), a))
['2', '3']
>>> b = [[1,2,3],[1,2],[1,2,3,4],[12,1,2]]
>>> list(reduce(lambda x,y : set(x) & set(y), b))
[1, 2]
合并字典value值
>>> mydict = {0:"hello ", 1:"world"}
>>> mylist =reduce(lambda x, y : x + y, mydict.values())
>>> mylist
'hello world'
>>> mydict = {0:[1,2,3,4], 1:[2,3,4,5,6]}
>>> mylist = list(reduce(lambda x, y : x + y, mydict.values()))
>>> mylist
[1, 2, 3, 4, 2, 3, 4, 5, 6]
>>> field_counters = dict(Counter(mylist))
>>> field_counters
{1: 1, 2: 2, 3: 2, 4: 2, 5: 1, 6: 1}
文章标题:Python笔记:List相关操作
本文作者:hiyo
本文链接:https://blog.csdn.net/u010698107/article/details/112756727
欢迎关注公众号:「测试开发小记」及时接收最新技术文章!
内容总结
以上是互联网集市为您收集整理的Python笔记:List相关操作全部内容,希望文章能够帮你解决Python笔记:List相关操作所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。