为了账号安全,请及时绑定邮箱和手机立即绑定

python有哪些方法可让list中的元素重复N次?

python有哪些方法可让list中的元素重复N次?

素胚勾勒不出你 2018-07-16 10:39:53
假设list a=["sf","342"....]我要让每一次一个元素重复2次,得到 ["sf","sf","342","342"....]有哪些比较好的方法呢?希望不影响list中顺序我现在的做法是a=["sf","342"....]*2然后a=sorted(a),但是考虑实际情况中可能不能使用sorted打乱顺序。所以想求好更好的办法。
查看完整描述

1 回答

?
海绵宝宝撒

TA贡献1809条经验 获得超8个赞

from itertools import chain, repeat
from functools import partial, reduce
this_is_a_list = [1, 2, 3, 4, 5]
what_you_want = reduce(
    chain, map(list, map(partial(reduce, times=2), this_is_a_list)))
this_is_a_list = [1, 2, 3, 4, 5]
what_you_want = [val for val in this_is_a_list for i in range(2)]


查看完整回答
反对 回复 2018-07-18
  • 1 回答
  • 0 关注
  • 2920 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信