oak*_*kca 4 python string dictionary list
我有一个通过python字典键组成的列表; list(dict.keys())。
dict.keys()
dict_keys(['South', 'North'])
Run Code Online (Sandbox Code Playgroud)
我想在类似的每个元素中添加一个字符串list = ['South', 'North']:
my_string = 'to_'
最后我想要 list = ['to_South', 'to_North']
有什么我可以使用的方法吗?
就像是:
list.add_beginning_of_each_element('to_')
Run Code Online (Sandbox Code Playgroud)
使用列表理解:
lst = ['South', 'North']
result = ['to_' + direction for direction in lst]
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用map:
def add_to_beginning(s, start='to_'):
return start + s
lst = ['South', 'North']
result = list(map(add_to_beginning, lst))
print(result)
Run Code Online (Sandbox Code Playgroud)
或map:
>>> l = ['South', 'North']
>>> list(map('to_'.__add__,l))
['to_South', 'to_North']
>>>
Run Code Online (Sandbox Code Playgroud)
有没有add_prefix在pandas,所以如果你有一个熊猫据帧,你可以使用add_prefix添加到列,使得数据帧进行列表,并让他们为列的例子:
>>> import pandas as pd
>>> pd.DataFrame(columns=['South', 'North']).add_prefix('to_').columns.tolist()
['to_South', 'to_North']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
692 次 |
| 最近记录: |