比如a = [1, 2, 3], b = [4, 5, 6]
合并为[1, 4, 2, 5, 3, 6]
你觉得怎么写比较优雅?
修正: 之前的代码有问题, 更新一次..
不知道算不算优雅, 但应该省内存:
def xmerge(a, b):
alen, blen = len(a), len(b)
mlen = min(alen, blen)
for i in xrange(mlen):
yield a[i]
yield b[i]
if alen > blen:
for i in xrange(mlen, alen):
yield a[i]
else:
for i in xrange(mlen, blen):
yield b[i]
a = [1, 2, 3]
b = [5, 6, 7, 8, 9, 10]
c = [i for i in xmerge(a, b)]
print c
c = [i for i in xmerge(b, a)]
print c
原来stackoverflow已经讨论过,写法都很吊哦。我个人很喜欢这个:
调用的cycle/islice函数都来自itertools
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
pending = len(iterables)
nexts = cycle(iter(it).next for it in iterables)
while pending:
try:
for next in nexts:
yield next()
except StopIteration:
pending -= 1
nexts = cycle(islice(nexts, pending))
python
def xmerge(a, b): tmp = (list(a), list(b)); return [tmp[i%2].pop(0) if tmp[i%2] else tmp[1-i%2].pop(0) for i in xrange(0, len(a) + len(b))] print xmerge([1,2,3], [5,6,7,8,9]) print xmerge([1,2,3,4,5], [7,8,9])
这样?
//写到一半搜了下python的三元表达式想起以前也是这种神兽飞过的心情用python的……
//不过还有三元写成if a then b else c
的语言,现在还是能理解了……
python3.3
result = [list(zip(a, b))[i][j] for i in range(len(a)) for j in range(len(list(zip(a, b))[0]))]
虽然是一行,但是有点牵强,小括号太多
python
# Python 3 def interpolate(*seqs): for items in zip(*seqs): yield from items >>> list(interpoltae('string', 'asdfgh')) ['s', 'a', 't', 's', 'r', 'd', 'i', 'f', 'n', 'g', 'g', 'h']
有个问题,如果这几个序列不都等长该怎么办。上面的解法是按长度最小的来:
python
>>> list(interpolate('string', 'asdf')) ['s', 'a', 't', 's', 'r', 'd', 'i', 'f']
但是如果不按最小的来该怎么办?补字符?补什么字符?
优雅的做数据处理,scipy系列库还是需要的。
有现成matplotlib中的flatten函数可以用。
from matplotlib.cbook import flatten
a = [1, 2, 3]
b = [4, 5, 6]
list(flatten(zip(a,b)))
不知道该如何去掉for语句,请教各位。
a = [1, 2, 3]
b = [4, 5, 6]
ans = []
for item in zip(a, b):
ans += list(item)
print(ans)
输入结果是:
-->[1, 4, 2, 5, 3, 6]
a = [1, 2, 3]
b = [4, 5, 6]
def slove(a, b):
c = []
i = 0
j = 0
while i<len(a) and j<len(b):
c.append(a[i])
c.append(b[j])
i += 1
j += 1
while i < len(a):
c.append(a[i])
i += 1
while j < len(b):
c.append(b[j])
j += 1
print(c)
if name == 'main':
slove(a, b)
a = [1,2,3]
b = [4,5,6]
s = []
for i in zip(a,b):s.extend(list(i))
print s
[1, 4, 2, 5, 3, 6]
4 回答4.5k 阅读✓ 已解决
1 回答3.5k 阅读✓ 已解决
4 回答3.9k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
2 回答549 阅读✓ 已解决
1 回答4.6k 阅读✓ 已解决
1 回答4k 阅读✓ 已解决