Bru*_*uce 2 python sorting string list
我正在尝试对字符串进行排序(为punnetsquare制作基因型).我目前的实施是:
unsorted_genotype = 'ABaB'
sorted_genotype = sorted(list(unsorted_genotype))
sorted_string = ''.join(sorted_genotype)
Run Code Online (Sandbox Code Playgroud)
它输出
'ABBa'
Run Code Online (Sandbox Code Playgroud)
虽然,我希望并期望:
'AaBB'
Run Code Online (Sandbox Code Playgroud)
我该如何更改或修复此问题?
您可以指定排序键并使用元组排序:
[(1,1),(1,2)]:元组按第1个元素排序,相等于第2个到第n个:
unsorted = 'ABaB'
s = sorted(unsorted, key= lambda x:(x.lower(),x))
print(''.join(s)) # 'AaBB'
Run Code Online (Sandbox Code Playgroud)
这可以确保它首先按"较低"字符排序 - 分组a和A 一起,然后按实际字符排序,这样它们也会排序:ABaaAAaAaAAAB => AAAAAAAaaaaBB
Readups:
一个简单的key = str.lower如allegated欺骗建议不组A到A和a到a这将是不错的Prunnet广场
如果你让它们按照出现顺序排列然后将小写和大写分组在一起,你可以使用:
unsorted = 'ABaaAAaAaAAAB'
s = sorted(unsorted, key=str.lower) # not by tuple, just by lower
print(''.join(s))
Run Code Online (Sandbox Code Playgroud)
导致元素"按顺序":
AaaAAaAaAAABB # instead of AAAAAAAaaaaBB
Run Code Online (Sandbox Code Playgroud)
并且在不区分大小写的列表排序中描述,而不降低结果?
| 归档时间: |
|
| 查看次数: |
75 次 |
| 最近记录: |