[英]Removing punctuation from only the beginning and end of each element in a list in 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']
正則表達式的一個很好的例子:
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.