[英]Sorting a list with strings and int. Only sorting int Python
Having trouble sorting a list with str and int.无法使用 str 和 int 对列表进行排序。 I want my code to return only listing int in asd and excluding str.
我希望我的代码只返回在 asd 中列出 int 并排除 str 。
def data(data_list):
for i, n in enumerate(data_list):
mn = min(range(i,len(data_list)), key=data_list.__getitem__)
data_list[i], data_list[mn] = data_list[mn], n
return data_list
data([8,11,10,9,4,3])
#returns this
[3, 4, 8, 9, 10, 11] # which is great but when the list includes str it does not run
#trying to run this
data([8,11,'b',9,4,'a'])
# want to return this
[3, 4, 8, 9]
#Also my code is quite confusing. I am sure there is a simpler way
You can simply use the built-in sorted()
function and filter out items that are not integers using a list comprehension like so:您可以简单地使用内置的
sorted()
函数并使用列表理解过滤掉不是整数的项目,如下所示:
>>> datastr = [8, 11, 'b', 9, 4, 'a']
>>> sorted([v for v in datastr if isinstance(v, int)])
[4, 8, 9, 11]
You can use isinstance(i, int)
to check if a particular object is of type int.您可以使用
isinstance(i, int)
来检查特定对象是否为 int 类型。
def data(data_list):
return sorted([o for o in data_list if isinstance(o, int)])
If any on the numbers are strings, you can deal with them using a helper function like below如果数字上有任何字符串,您可以使用如下所示的辅助函数处理它们
def intHelper(o):
if isinstance(o, int):
return o
elif isinstance(o, str):
try:
return int(o)
except ValueError:
return None
return None
def data(data_list):
return sorted([o for o in list(map(intHelper, data_list)) if o is not None])
data = ['5',4,3,2,1.1,'zero','-1','0.4'] sorted_data = [] for datum in data: try: if isinstance(datum,str): if '.' in datum: sorted_data.append(float(datum)) else: sorted_data.append(int(datum)) else: if isinstance(datum,int): sorted_data.append(int(datum)) else: sorted_data.append(float(datum)) except: pass sorted_data.sort() print(sorted_data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.