add a character to each item in a list

匿名 (未验证) 提交于 2019-12-03 03:05:02

问题:

Suppose I have a list of suits of cards as follows:

suits = ["h","c", "d", "s"]

and I want to add a type of card to each suit, so that my result is something like

aces = ["ah","ac", "ad", "as"]

is there an easy way to do this without recreating an entirely new list and using a for loop?

回答1:

This would have to be the 'easiest' way

>>> suits = ["h","c", "d", "s"] >>> aces = ["a" + suit for suit in suits] >>> aces ['ah', 'ac', 'ad', 'as'] 


回答2:

Another alternative, the map function:

aces = map(( lambda x: 'a' + x), suits) 


回答3:

If you want to add something different than always 'a' you can try this too:

foo = ['h','c', 'd', 's'] bar = ['a','b','c','d'] baz = [x+y for x, y in zip(foo, bar)] >>> ['ha', 'cb', 'dc', 'sd'] 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!