簡體   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