获取具有特定条件的数组中的某些元素 [英] Get some element in an array with a specific condition
本文介绍了获取具有特定条件的数组中的某些元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好我有一个问题:
如果我有这个数组:dd = [(1,'a',2),(2,'b',4),(5,' a',4)]
i想从dd / d1获得d1 = [(1,'a',2),(5,'a',4)]为dd [i] [1] ='a'
我怎么样?
我尝试过:
>>> d1 = [dd为dd [i] [1] ='a'为i,范围为(0,3)]
文件< stdin>,第1行
d1 = [dd for dd [i] [1] ='a'表示i在范围(0,3)中
^
语法错误:语法无效
hello i have a question:
if i have this array : dd=[(1,'a',2),(2,'b',4),(5,'a',4)]
i want to get only d1 from dd / d1=[(1,'a',2),(5,'a',4)] for dd[i][1]='a'
how i can?
What I have tried:
>>> d1=[dd for dd[i][1]='a' for i in range(0,3)]
File "<stdin>", line 1
d1=[dd for dd[i][1]='a' for i in range(0,3)]
^
SyntaxError: invalid syntax
推荐答案
你有一个元组列表,为了获得第二个元素为'a'的元组,使用这样的列表解析:
You have a list of tuples, to get those tuples whose second element is 'a', make use of list comprehension like this:
dd=[(1,'a',2),(2,'b',4),(5,'a',4)]
d1=[x for x in dd if x[1] == 'a']
print (d1)
你应该得到
[(1, 'a', 2), (5, 'a', 4)]
参见 Python教程 - Python 3.4.5文档 [ ^ ]。
使用列表理解,例如:
See The Python Tutorial — Python 3.4.5 documentation[^].
Use a list comprehension such as:
[x for x in dd if x[1]=='a']
给出: [(1,'a',2),( 5,'a',4)]
这篇关于获取具有特定条件的数组中的某些元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文