[英]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.