简体   繁体   English

如何根据浮动元素过滤列表?

[英]How to filter a list of floats based on their elements?

I'm fairly new to programming. 我是编程新手。

Basically in a list of floats, I want my program to print every one that starts with either '1' or '-1'. 基本上在浮点列表中,我希望我的程序打印以'1'或'-1'开头的每个浮点数。 This is what I have so far. 到目前为止,这就是我所拥有的。

def oneminus(L):  
    for i in range(len(L)):  
        if L[i][0]=='1':  
            print(L[i])  
        elif L[i][0]=='-' and L[i][1]=='1':  
            print(L[i])

When I run the program however I get the error "TypeError: 'float' object is not subscriptable" So I'm assuming the issue is due to the fact the list contains floats. 但是,当我运行程序时,出现错误“ TypeError:'float'对象不可下标”,因此我假设问题是由于列表包含浮点数。

The problem is that you're treating the elements as strings, not floats. 问题在于您将元素视为字符串,而不是浮点数。 Unlike PHP and Javascript, Python doesn't have implicit type coercion. 与PHP和Javascript不同,Python没有隐式类型强制。 If you want to get the string representation, you have to convert it explicitly using str or repr . 如果要获取字符串表示形式,则必须使用strrepr对其进行显式转换。

What you want is something like 你想要的是像

def oneminus(L): 
    for x in L:
        if str(x).startswith('1') or str(x).startswith('-1'):
            print(x)

You could make it shorter by taking advantage of str.strip . 您可以利用str.strip将其缩短。

def oneminus(L): 
    for x in L:
        if str(x).strip('-').startswith('1'):
            print(x)

Also note that you can iterate over a list directly. 还请注意,您可以直接遍历列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM