给出向量列表:
[((0, 2.6147858445098677), (1, 1.0257184186249431)), ((0, 2.6147858445098677), (2, 0.34113605903013322)), ((0, 2.6147858445098677), (3, 0.074196986667672063)), ((1, 1.0257184186249431), (2, 0.34113605903013322)), ((1, 1.0257184186249431), (3, 0.074196986667672063)), ((2, 0.34113605903013322), (3, 0.074196986667672063))]
如何仅提取每个向量中的第一个条目?
[(0, 1), (0,2), (0, 3), (1, 2), (1,3), (2, 3)]
答案 0 :(得分:4)
可以只使用列表推导。每个项目都是一个包含两个元组的元组,因此我们可以像这样解析每个内部元组的第一个项目:
x = [((0, 2.6147858445098677), (1, 1.0257184186249431)), ((0, 2.6147858445098677), (2, 0.34113605903013322)), ((0, 2.6147858445098677), (3, 0.074196986667672063)), ((1, 1.0257184186249431), (2, 0.34113605903013322)), ((1, 1.0257184186249431), (3, 0.074196986667672063)), ((2, 0.34113605903013322), (3, 0.074196986667672063))]
result = [(item[0][0], item[1][0]) for item in x]
print(result)
输出:
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
根据需要。这是非常c的样式,如果需要,您可以使用pythonic并使用元组拆包:
result = [(first[0], second[0]) for first, second in x]
这更易于理解/阅读。
答案 1 :(得分:0)
或map
:
>>> l=[((0, 2.6147858445098677), (1, 1.0257184186249431)), ((0, 2.6147858445098677), (2, 0.34113605903013322)), ((0, 2.6147858445098677), (3, 0.074196986667672063)), ((1, 1.0257184186249431), (2, 0.34113605903013322)), ((1, 1.0257184186249431), (3, 0.074196986667672063)), ((2, 0.34113605903013322), (3, 0.074196986667672063))]
>>> list(map(lambda x: (x[0][0],x[1][0]),l))
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
>>>
答案 2 :(得分:0)
lista =[
((0, 2.6147858445098677), (1, 1.0257184186249431)),
((0, 2.6147858445098677), (2, 0.34113605903013322)),
((0, 2.6147858445098677), (3, 0.074196986667672063)),
((1, 1.0257184186249431), (2, 0.34113605903013322)),
((1, 1.0257184186249431), (3, 0.074196986667672063)),
((2, 0.34113605903013322), (3, 0.074196986667672063)) ]
new_lista = []
for i in lista:
new_lista.append((i[0][0], i[1][0]))
print(new_lista)
或者:
[new_lista.append((i[0][0], i[1][0])) for i in lista]
(xenial)vash@localhost:~/python/stack_overflow$ python3.7 vector.py [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
答案 3 :(得分:0)
出于完整性考虑,您还可以使用operator.itemgetter
,map
和functools.partial
的组合(给定列表v
):
from operator import itemgetter
from functools import partial
list(map(tuple, map(partial(map, itemgetter(0)), v)))
或者在Python 2.7或更早的版本中可以更加简洁:
map(partial(map, itemgetter(0)), v)