简体   繁体   English

如何从 PYTHON I 中以“A”开头的列表中提取单词?

[英]How do I extract words from a list that start with “A” in PYTHON I?

The directions say "Use the following initializer list:说明说“使用以下初始化列表:

w = ["Algorithm", "Logic", "Filter", "Software", "Network", "Parameters", "Analyze", "Algorithm", "Functionality", "Viruses"] Write a loop to print the words that start with "A". w = ["Algorithm", "Logic", "Filter", "Software", "Network", "Parameters", "Analyze", "Algorithm", "Functionality", "Viruses"] 写一个循环来打印单词以“A”开头。

Sample Run Algorithm Analyze Algorithm"样本运行算法分析算法"

I tried to do it with the following code:我尝试使用以下代码来做到这一点:

w = ["Algorithm", "Logic", "Filter", "Software", "Network", "Parameters", "Analyze", "Algorithm", "Functionality", "Viruses"]

for i in range(len(w)):
     if (i[0] == "a" or i[0] == "A"):
          print(w[i])

but I keep getting the error "Line 4: TypeError: 'int' does not support indexing"但我不断收到错误“第 4 行:TypeError:'int' 不支持索引”

pls help请帮忙

You can use a list comprehension for this您可以为此使用列表推导

>>> [word for word in w if word[0].upper() == 'A']
['Algorithm', 'Analyze', 'Algorithm']

If you want to be case-specific (ie do not match both 'a' and 'A' ) you can remove the .upper()如果您想区分大小写(即不匹配'a''A' ),您可以删除.upper()

You forgot to get the word out of the list and instead were trying to get the first character of the index (i), which obviously doesn't work.您忘记将单词从列表中取出,而是试图获取索引 (i) 的第一个字符,这显然不起作用。

w = ["Algorithm", "Logic", "Filter", "Software", "Network", "Parameters", "Analyze", "Algorithm", "Functionality", "Viruses"]

for i in range(len(w)):
     if (w[i][0] == "a" or w[i][0] == "A"):
          print(w[i])

However a more "pythonic" way of iterating over a list is as follows:然而,一种更“pythonic”的迭代列表的方式如下:

for word in w:
     if (word[0] == "a" or word[0] == "A"):
          print(word)

How do I extract words from a list that start with “A”如何从以“A”开头的列表中提取单词

str.startswith does exactly that: str.startswith正是这样做的:

Return True if string starts with the prefix, otherwise return False.如果字符串以前缀开头,则返回 True,否则返回 False。 prefix can also be a tuple of prefixes to look for. prefix 也可以是要查找的前缀元组。 With optional start, test string beginning at that position.使用可选开始,测试从 position 开始的字符串。 With optional end, stop comparing string at that position.使用可选结束,停止比较该 position 处的字符串。

>>> [word for word in w if word.startswith("A")]
['Algorithm', 'Analyze', 'Algorithm']

Another easier approach:另一种更简单的方法:

for word in w:
    if word.startswith("A"):
        print(word)

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

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