繁体   English   中英

仅从在python中元素开头具有任何数量的列表中获取元素

[英]Only get the elements from a list that has any kind of quantity in the beginning of the element in python

我使用逗号分隔符从带有 split 函数的字符串创建了一个列表。 该列表如下所示:

mylist = ['2       boneless skinless chicken breast halves', ' cut into thin strips ', '4   ounces    linguine', ' cooked al dente ', '2   teaspoons    cajun seasoning (your recipe', ' \\u003ca href\\u003d\\"https://www.geniuskitchen.com/recipe/cajun-seasoning-mix-14190\\"\\u003eCajun Seasoning Mix\\u003c/a\\u003e or store-bought)', '2   tablespoons    butter', '1      thinly sliced green onion', '1/2  cup    heavy whipping cream', '2   tablespoons   chopped sun-dried tomatoes', '1/4  teaspoon    salt', '1/4  teaspoon    dried basil', '1/8  teaspoon    ground black pepper', '1/8  teaspoon    garlic powder', '1/4  cup   grated parmesan cheese']

现在我想得到list[0]元素,因为它在前面有一个整数,但我不想要list[1]因为它没有整数。 List[0]在开头有一个像 2 这样的整数。 它也可能是 1/2 杯之类的东西。 所以我只想获取一开始具有任何数量值的列表项。 其他物品我会丢弃。 如何过滤这些元素? 任何帮助都非常感谢。 提前致谢

正则表达式的一个很好的例子:

import re

mylist = ['2       boneless skinless chicken breast halves',
          ' cut into thin strips ', '4   ounces    linguine',
          ' cooked al dente ', '2   teaspoons    cajun seasoning (your recipe',
          ' \\u003ca href\\u003d\\"https://www.geniuskitchen.com/recipe/cajun-seasoning-mix-14190\\"\\u003eCajun Seasoning Mix\\u003c/a\\u003e or store-bought)',
          '2   tablespoons    butter', '1      thinly sliced green onion', '1/2  cup    heavy whipping cream', '2   tablespoons   chopped sun-dried tomatoes', '1/4  teaspoon    salt', '1/4  teaspoon    dried basil', '1/8  teaspoon    ground black pepper', '1/8  teaspoon    garlic powder', '1/4  cup   grated parmesan cheese']

rx = re.compile(r'\d+(?:/\d+)?')

filtered = [item
            for item in mylist
            if rx.match(item)]
print(filtered)


这里的表达是

\\d+(?:/\\d+)?

一个简单的理解,应该完全符合你的描述。 它检查第一个字符是否是数字,如果是,则将字符串附加到新列表中。

newy = [s for s in y if s[0].isdigit()]

暂无
暂无

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

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