我怎样才能得到这个
nums = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8)]
对此?每个元组的第二项是下一元组的第一项。
[0, 1, 2, 3, 4, 5, 6, 7, 8]
我做了:
>>> zip(*nums)[0]
(0, 1, 2, 3, 4, 5, 6, 7)
但它给了我除了最后一个元素之外的所有内容然后我不得不使用一些不好的代码来获得正确的结果,所以我正在寻找一个优雅的解决方案。
答案 0 :(得分:5)
不确定您的一般情况,但
[nums[0][0]] + [x[1] for x in nums]
为您的例子
range(nums[-1][-1] + 1)
也有效,你能描述一下你想做什么而不仅仅是给出一个简单的案例吗?
答案 1 :(得分:4)
>>> nums = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8)]
>>> i = iter(nums)
>>> next(i) + tuple(y for x,y in i)
(0, 1, 2, 3, 4, 5, 6, 7, 8)
使用itertools
>>> from itertools import chain
>>> nums = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8)]
>>> i = iter(nums)
>>> list(chain(next(i),(y for x,y in i)))
[0, 1, 2, 3, 4, 5, 6, 7, 8]
答案 2 :(得分:0)
def flatten(E):
if E in [[], ()]:
return []
elif type(E) not in [list, tuple]:
return [E]
else:
return flatten(E[0]) + flatten(E[1:])
def declutter(L):
s = set()
answer = []
for i in L:
if i not in s:
s.add(i)
answer.append(i)
return answer
>>> nums = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8)]
>>> declutter(flatten(nums))
[0, 1, 2, 3, 4, 5, 6, 7, 8]
希望这有帮助