python – 将列表中的每个项目加倍

python – 将列表中的每个项目加倍,第1张

概述如何在不使用任何导入的情况下将列表中的每个项目加倍? 一些例子: >>> multiply_items(['a', 'b'])['a', 'a', 'b', b']>>> multiply_items(['b', 'a'])['b', 'b', 'a', a']>>> multiply_items(['a', 'b', 'c'])['a', 'a', 'b', b', 'c', c'] 如何在不使用任何导入的情况下将列表中的每个项目加倍?

一些例子:

>>> multiply_items(['a','b'])['a','a','b',b']>>> multiply_items(['b','a'])['b',a']>>> multiply_items(['a','c'])['a',b','c',c']>>> multiply_items(['3','4'])['3','3','4',4']>>> multiply_items(['hi','bye'])['hi','hi','bye',bye']

这是我想出来的,但它将元素组合在一起而不是单独的字符串.

def multiply_items(sample_List):    '''(List) -> List    Given a List,returns the a new List where each element in the List is    doubled.    >>> multiply_items(['a','b'])    ['a',b']    >>> multiply_items(['a','c'])    ['a',c']    >>> multiply_items(['3','4'])    ['3',4']    '''    new_List = []    for item in sample_List:        new_List.append(item * 2)    return new_List

我得到的输出:

>>> multiply_items(['3','4'])['33','44']>>> multiply_items(['hi','bye'])['hihi','byebye']

谢谢你的帮助:)

解决方法 如此接近…天真的方法:

for item in sample_List:    for i in range(2):        new_List.append(item)

你的问题是由字符串也是列表这一事实引起的,因此’a’* 2不是[‘a’,’a’]而是aa.现在,知道问题,您仍然可以通过在单例列表中移动项目来在单个循环中解决它:更好的方法:

for item in sample_List:    new_List.extend([item] * 2)
总结

以上是内存溢出为你收集整理的python – 将列表中的每个项目加倍全部内容,希望文章能够帮你解决python – 将列表中的每个项目加倍所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/1192975.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存