Python 为列表中的每一项添加一个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15738267/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:50:34  来源:igfitidea点击:

add a character to each item in a list

python

提问by fox

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

假设我有一张牌的列表,如下所示:

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

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"]

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

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

有没有一种简单的方法可以在不重新创建一个全新的列表和使用for循环的情况下做到这一点?

采纳答案by jamylak

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']

回答by b2Wc0EKKOvLPn

Another alternative, the map function:

另一种选择,地图功能:

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

回答by bobrobbob

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

如果你想添加一些不同于 'a' 的东西,你也可以试试这个:

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