python list 去空元素的元素怎么去

追求卓越,成功就会在不经意间追上你!
对python中list的操作,大家可以参考:
以下是我个人的笔记:
============================================
Add by Hongten
============================================
1 #python list
创建list有很多方法:
1.使用一对方括号创建一个空的list:[]
2.使用一对方括号,用','隔开里面的元素:[a, b, c], [a]
3.Using a list comprehension:[x for x in iterable]
4.Using the type constructor:list() or list(iterable)
12 def create_empty_list():
'''Using a pair of square brackets to denote the empty list: [].'''
16 def create_common_list():
'''Using square brackets, separating items with commas: [a], [a, b, c].'''
return ['a', 'b', 'c', 1, 3, 5]
21 def create_common_list2():
'''Using a list comprehension: [x for x in iterable].'''
return [x for x in range(1, 10)]
25 def str_to_list(s):
'''Using a string to convert list'''
if s != None:
return list(s)
32 def main():
test_listA = create_empty_list()
print(test_listA)
print('#' * 50)
test_listB = create_common_list()
print(test_listB)
print('#' * 50)
test_listC = create_common_list2()
print(test_listC)
print('#' * 50)
test_str = 'i want to talk about this problem!'
test_listD = str_to_list(test_str)
print(test_listD)
47 if __name__ == '__main__':
运行效果:
Python 3.3.2 (v3.3.2:df6, May 16 :43) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
&&& ================================ RESTART ================================
##################################################
['a', 'b', 'c', 1, 3, 5]
##################################################
[1, 2, 3, 4, 5, 6, 7, 8, 9]
##################################################
['i', ' ', 'w', 'a', 'n', 't', ' ', 't', 'o', ' ', 't', 'a', 'l', 'k', ' ', 'a', 'b', 'o', 'u', 't', ' ', 't', 'h', 'i', 's', ' ', 'p', 'r', 'o', 'b', 'l', 'e', 'm', '!']
下面有更多的demo:
1 Python 3.3.2 (v3.3.2:df6, May 16 :43) [MSC v.1600 32 bit (Intel)] on win32
2 Type "copyright", "credits" or "license()" for more information.
3 &&& counter = 100
4 &&& miles = 1000.0
5 &&& name = "hongten"
6 &&& numberA,numberB,nameC = 1,2,"Hongten"
7 &&& list = [counter,miles,name,numberA,numberB,nameC]
8 &&& print(list)
9 [100, 1000.0, 'hongten', 1, 2, 'Hongten']
10 &&& #这是注释部分,注释用"#"开始
11 &&& for element in list:
print(element)
16 hongten
19 Hongten
20 &&& #上面是遍历列表list
21 &&& print(list[0]) #获取列表list里面的第一个元素值
23 &&& print(list[-1]) #获取列表list里面的最后一个元素值
24 Hongten
25 &&& print(len(list)) #用len(list)获取list列表的长度
27 &&& num_inc_list = range(10) #产生一个数值递增的列表
28 &&& print(num_inc_list)
29 range(0, 10)
30 &&& for inc_list in num_inc_list:
print(inc_list)
43 &&& #从这里我们可以看到range(10)是产生了一个从0开始到9的一个数值递增列表
44 &&& initial_value = 10
45 &&& list_length = 5
46 &&& myList = [initial_value for i in range(10)]
47 &&& print(myList)
48 [10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
49 &&& list_length = 2
50 &&& myList = myList * list_length
51 &&& print(myList)
52 [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
53 &&& print(len(myList))
55 &&& #上面是用一个固定值initial_value去初始化一个列表myList
56 &&& #同时用myList = myList * list_length去复制myList
57 &&& #下面再看看复制的效果
58 &&& copyList = [1,2,3,"hongten"]
59 &&& copyList = copyList * list_length
60 &&& print(len(copyList))
62 &&& for cl in copyList:
69 hongten
73 hongten
74 &&& #下面我们来仔细研究一下python里面的list
75 &&& #在一个list中可以包含不同类型的元素,这个和ActionScript 3.0(AS3.0)中的数组类似
76 &&& test_list = ["hello",1,2,"world",4,5,"hongten"]
77 &&& print(len(test_list))
79 &&& print(test_list[0]) # 打印test_list
81 &&& #打印test_list中的第一元素
82 &&& print(test_list[-1]) #打印test_list中最后一个元素
83 hongten
84 &&& print(test_list[-len]) #打印第一个元素
85 Traceback (most recent call last):
File "&pyshell#44&", line 1, in &module&
print(test_list[-len]) #打印第一个元素
88 TypeError: bad operand type for unary -: 'builtin_function_or_method'
89 &&& print(test_list[-len(test_list)]) #打印第一个元素
91 &&& print(test_list[len(test_list) - 1]) #打印最后一个元素
92 hongten
93 &&& test_list.append(6) #向列表中追加一个元素
94 &&& print(test_list[-1])
96 &&& test_list.insert(1,0)
97 &&& print(test_list)
98 ['hello', 0, 1, 2, 'world', 4, 5, 'hongten', 6]
99 &&& #上面的操作是向列表test_list的小标为1的地方插入元素0
100 &&& test_list.insert(1,0)
101 &&& print(test_list)
102 ['hello', 0, 0, 1, 2, 'world', 4, 5, 'hongten', 6]
103 &&& test_list.insert(2,1)
104 &&& print(test_list)
105 ['hello', 0, 1, 0, 1, 2, 'world', 4, 5, 'hongten', 6]
106 &&& print(test_list.pop(0)) #返回最后一个元素,并从test_list中删除之
108 &&& print(test_list)
109 [0, 1, 0, 1, 2, 'world', 4, 5, 'hongten', 6]
110 &&& print(test_list.pop(2)) #上面的注释有错误,pop(index)的操作是返回数组下标为index的元素,并从列表中删除之
112 &&& print(test_list)
113 [0, 1, 1, 2, 'world', 4, 5, 'hongten', 6]
114 &&& test_list.remove(1)
115 &&& print(test_list)
116 [0, 1, 2, 'world', 4, 5, 'hongten', 6]
117 &&& #remove(1)表示的是删除第一次出现的元素1
118 &&& test_list.insert(0,1)
119 &&& print(test_list)
120 [1, 0, 1, 2, 'world', 4, 5, 'hongten', 6]
121 &&& test_list.remove(1)
122 &&& print(test_list)
123 [0, 1, 2, 'world', 4, 5, 'hongten', 6]
124 &&& test_list.insert(2,"hongten")
125 &&& print(test_list)
126 [0, 1, 'hongten', 2, 'world', 4, 5, 'hongten', 6]
127 &&& test_list.count("hongten")
129 &&& #count(var)是统计var元素在列表中出现的个数
130 &&& test_list.count("foo")
132 &&& test_list_extend = ["a","b","c"]
133 &&& test_list.extend(test_list_extend)
134 &&& print(test_list)
135 [0, 1, 'hongten', 2, 'world', 4, 5, 'hongten', 6, 'a', 'b', 'c']
136 &&& #使用extend(list)作用是追加一个list到源list上面
137 &&& print(test_list.sort())
138 Traceback (most recent call last):
File "&pyshell#76&", line 1, in &module&
print(test_list.sort())
141 TypeError: unorderable types: str() & int()
142 &&& test_list_extend.append("h")
143 &&& test_lsit_extend.append("e")
144 Traceback (most recent call last):
File "&pyshell#78&", line 1, in &module&
test_lsit_extend.append("e")
147 NameError: name 'test_lsit_extend' is not defined
148 &&& list_a = ["e","z","o","r"]
149 &&& list_a.extend(test_list_extend)
150 &&& print(list_a)
151 ['e', 'z', 'o', 'r', 'a', 'b', 'c', 'h']
152 &&& print(list_a.sort()) #对list_a列表进行排序
154 &&& #不知道为什么以上排序都有报错......
155 &&& list_b = [1,3,5,2,6,4]
156 &&& print(list_b.sort())
158 &&& print(sort(list_b))
159 Traceback (most recent call last):
File "&pyshell#86&", line 1, in &module&
print(sort(list_b))
162 NameError: name 'sort' is not defined
163 &&& #不去管排序问题了,先看看删除操作吧!!!!!
164 &&& print(list_b)
165 [1, 2, 3, 4, 5, 6]
166 &&& print(del list_b[1])
167 SyntaxError: invalid syntax
168 &&& del list_b[1]
169 &&& print(list_b)
170 [1, 3, 4, 5, 6]
171 &&& del list_b[0,2]
172 Traceback (most recent call last):
File "&pyshell#92&", line 1, in &module&
del list_b[0,2]
175 TypeError: list indices must be integers, not tuple
176 &&& del list_b[0:2]
177 &&& print(list_b)
178 [4, 5, 6]
180 &&& #del list[index]删除下标为index的元素,del list[start:end]删除从start下标开始到end下标结束的元素
181 &&& del list_b[10]
182 Traceback (most recent call last):
File "&pyshell#96&", line 1, in &module&
del list_b[10]
185 IndexError: list assignment index out of range
186 &&& #如果我们删除的下标超出了列表的长度范围,就会报错啦!!!!!
187 &&& ##########################################################################
188 &&& list_c = range(5);
189 &&& for c in list_c:
198 &&& list_d = list_c
199 &&& for d in list_d:
208 &&& #上面是列表的复制
209 &&& list_d[2] = 23
210 Traceback (most recent call last):
File "&pyshell#108&", line 1, in &module&
list_d[2] = 23
213 TypeError: 'range' object does not support item assignment
214 &&& list_e = [1,2,3,4,5]
215 &&& list_f = list_e
216 &&& list_f[2] = 234
217 &&& print(list_e)
218 [1, 2, 234, 4, 5]
219 &&& #从这里我们可以知道,list_f复制了list_e,list_f是对list_e的一个引用,
220 &&& #他们共同指向一个对象:[1,2,3,4,5],当我们视图修改list_f[2]的值的时候,
221 &&& #list_f所指向的对象的行为发生了变化,即元素值发生了变化,但是他们的引用是没有
222 &&& #发生变化的。所以list_e[2] = 234也是在情理之中。
223 &&& #######################################################################
224 &&& list_i = list_e[:]
225 &&& print(list_i)
226 [1, 2, 234, 4, 5]
227 &&& print(list_e)
228 [1, 2, 234, 4, 5]
229 &&& list_i[2] = 3
230 &&& print(list_e)
231 [1, 2, 234, 4, 5]
232 &&& print(list_i)
233 [1, 2, 3, 4, 5]
234 &&& #上面是进行了列表的克隆操作,即拷贝了另一个列表,这样的操作,会创造出新的一个列表对象
235 &&& #使得list_i和list_e指向不同的对象,就有着不同的引用,所以当list_i[2] = 3的时候,
236 &&& #list_e[2]还是等于234,即不变
阅读(...) 评论()2012年1月 其他开发语言大版内专家分月排行榜第二2011年5月 其他开发语言大版内专家分月排行榜第二2010年12月 其他开发语言大版内专家分月排行榜第二2009年2月 其他开发语言大版内专家分月排行榜第二2008年9月 其他开发语言大版内专家分月排行榜第二2008年8月 其他开发语言大版内专家分月排行榜第二2008年5月 其他开发语言大版内专家分月排行榜第二2007年11月 其他开发语言大版内专家分月排行榜第二
2011年4月 其他开发语言大版内专家分月排行榜第三2011年1月 其他开发语言大版内专家分月排行榜第三2009年6月 其他开发语言大版内专家分月排行榜第三2009年4月 其他开发语言大版内专家分月排行榜第三2009年1月 其他开发语言大版内专家分月排行榜第三2008年11月 其他开发语言大版内专家分月排行榜第三2008年7月 其他开发语言大版内专家分月排行榜第三2008年6月 其他开发语言大版内专家分月排行榜第三2006年9月 其他开发语言大版内专家分月排行榜第三
本帖子已过去太久远了,不再提供回复功能。Python 中如何删除一个列表 List 中多个符合条件的元素? - 知乎78被浏览52591分享邀请回答357 条评论分享收藏感谢收起from functools import reduce
a = [1, 1, 0, 2, 0, 0, 8, 3, 0, 2, 5, 0, 2, 6]
def reducer(acc, y):
if acc and acc[-1] == 0 and y == 2:
acc.append(y)
return acc
result = reduce(reducer, a, [])
assert result == [1, 1, 2, 0, 0, 8, 3, 2, 5, 2, 6]
这个方案,2前面如果有多个0,只会删除1个0(比较符合题主的意思)。但是如果需要删除多个0,就需要pop多次了:from functools import reduce
a = [1, 1, 0, 2, 0, 0, 8, 3, 0, 2, 5, 0, 0, 2, 6]
def reducer(acc, y):
if y == 2:
while acc and acc[-1] == 0:
acc.append(y)
return acc
result = reduce(reducer, a, [])
assert result == [1, 1, 2, 0, 0, 8, 3, 2, 5, 2, 6]
3添加评论分享收藏感谢收起查看更多回答1 个回答被折叠()3485人阅读
python(1)
在python中时常需要从字符串类型str中提取元素到一个数组list中,例如str是一个逗号隔开的姓名名单,需要将每个名字提取到一个元素为str型的list中。
如姓名列表str = 'Alice, Bob, John',需要将其提取为name_list = ['Alice', 'Bob', 'John']。
而反过来有时需要将一个list中的字符元素按照指定的分隔符拼接成一个完整的字符串。好在python中str类型本身自带了两种方法(method)提供了相应的功能。
str转为list
使用split方法
&list& = &str&.split(&separator&)
&str&: 需要进行分隔提取的字符串
&separator&:从&str2&提取元素时依据的分隔符,一般也是一个str类型,如','
&list&: 返回值,list中每个元素是&str&中分隔后的一个片段
str = 'abc,def,ghi'
a = str.split(',')
得到结果:
['abc','def','ghi']
list转换为str
使用join方法
&str& = &separator&.join(&list&)
&separator&: 分隔符,为str类型,如','
&list&: 需要进行合并的list对象,其中每个元素必须为str类型
&str&: 返回一个str对象,是将&list&中每个元素按顺序用分隔符&separator&拼接而成
a = ','.join(['abc','def','ghi'])
'abc,def,ghi'
注意:使用join方法时,括号内的参数list必须只包含str类型的成员 这两种方法均是str的方法,即.之前必须为str类型
与os.path.join()和os.path.split()的区别
在os模块中其系统路径分隔符对象os.path也有两个同名的方法join()和split(),使用和str中基本类似,其主要区别是str中同名方法的所有的list类型参数在这里均变成变成了tuple类型
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:15855次
排名:千里之外
原创:12篇问题对人有帮助,内容完整,我也想知道答案
问题没有实际价值,缺少关键内容,没有改进余地
如何将以下list去重
url_list = [
{'path': ['jy5', 'xhr', 'compose', 'init.do'], 'host': 'cwebmail.', 'method': 'POST', 'query': ['cType', 'sid']},
{'path': ['jy5', 'xhr', 'user', 'refresh.do'], 'host': 'cwebmail.', 'method': 'POST', 'query': ['sid']},
{'path': ['jy5', 'xhr', 'compose', 'compose.do'], 'host': 'cwebmail.', 'method': 'POST', 'query': ['action', 'sid']},
{'path': ['jy5', 'data', 'analytics.s'], 'host': 'cwebmail.', 'method': 'GET', 'query': ['product', 'uid', 'host', 'fun', 'data', '_']},
{'path': ['jy5', 'swf', 'upload2.swf'], 'host': 'cwebmail.', 'method': 'GET', 'query': []},
{'path': ['jy5', 'data', 'analytics.s'], 'host': 'cwebmail.', 'method': 'GET', 'query': ['product', 'uid', 'host', 'fun', 'data', '_']},
{'path': ['jy5', 'xhr', 'user', 'refresh.do'], 'host': 'cwebmail.', 'method': 'POST', 'query': ['sid']},
{'path': ['jy4-app', 'xhr', 'dropbox', 'account', 'check.do'], 'host': 'jy4-app.', 'method': 'POST', 'query': ['utoken', 'sid']}
转换成以下的list
url_list = [
{'path': ['jy5', 'xhr', 'compose', 'init.do'], 'host': 'cwebmail.', 'method': 'POST', 'query': ['cType', 'sid']},
{'path': ['jy5', 'xhr', 'user', 'refresh.do'], 'host': 'cwebmail.', 'method': 'POST', 'query': ['sid']},
{'path': ['jy5', 'xhr', 'compose', 'compose.do'], 'host': 'cwebmail.', 'method': 'POST', 'query': ['action', 'sid']},
{'path': ['jy5', 'data', 'analytics.s'], 'host': 'cwebmail.', 'method': 'GET', 'query': ['product', 'uid', 'host', 'fun', 'data', '_']},
{'path': ['jy5', 'swf', 'upload2.swf'], 'host': 'cwebmail.', 'method': 'GET', 'query': []},
{'path': ['jy4-app', 'xhr', 'dropbox', 'account', 'check.do'], 'host': 'jy4-app.', 'method': 'POST', 'query': ['utoken', 'sid']}
答案对人有帮助,有参考价值
答案没帮助,是错误的答案,答非所问
此list中元素为dict,是unhashable对象,使用直接set之后再list的方法去重会报错
TypeError: unhashable type: 'dict'
可以用下面的方法。
f = lambda x,y:x if y in x else x + [y]
url_list = reduce(f, [[], ] + url_list)
关于reduce(),请看
答案对人有帮助,有参考价值
答案没帮助,是错误的答案,答非所问
想到一个办法,不知道有没有更好的方法?欢迎回答
url_list_uniq = []
for url in url_list:
if url not in url_list_uniq:
url_list_uniq.append(url)
print url_list_uniq
答案对人有帮助,有参考价值
答案没帮助,是错误的答案,答非所问
把问题抽象一下更好,主要是代码段。抽象一下会更容易看。
答案对人有帮助,有参考价值
答案没帮助,是错误的答案,答非所问
urlListNew = []
while url_list:
url = url_list.pop()
if url not in urlListNew:
urlListNew.append(url)
print urlListNew
貌似我这个没第一个答案好...还破坏了原列表
同步到新浪微博
分享到微博?
你好!看起来你挺喜欢这个内容,但是你还没有注册帐号。 当你创建了帐号,我们能准确地追踪你关注的问题,在有新答案或内容的时候收到网页和邮件通知。还能直接向作者咨询更多细节。如果上面的内容有帮助,记得点赞 (????)? 表示感谢。
明天提醒我
关闭理由:
删除理由:
忽略理由:
推广(招聘、广告、SEO 等)方面的内容
与已有问题重复(请编辑该提问指向已有相同问题)
答非所问,不符合答题要求
宜作评论而非答案
带有人身攻击、辱骂、仇恨等违反条款的内容
无法获得确切结果的问题
非开发直接相关的问题
非技术提问的讨论型问题
其他原因(请补充说明)
我要该,理由是:

我要回帖

更多关于 python list 去空元素 的文章

 

随机推荐