简体   繁体   English

Python简介-列出问题

[英]Intro to Python - Lists questions

we've started doing Lists in our class and I'm a bit confused thus coming here since previous questions/answers have helped me in the past. 我们已经开始在课堂上做Lists了,我有点困惑,所以来到这里是因为以前的问题/答案在过去对我有所帮助。

The first question was to sum up all negative numbers in a list, I think I got it right but just want to double check. 第一个问题是对列表中的所有负数求和,我想我没错,但只想仔细检查。

import random

def sumNegative(lst):
    sum = 0
    for e in lst:
        if e < 0:
            sum = sum + e
    return sum

lst = []
for i in range(100):
    lst.append(random.randrange(-1000, 1000))

print(sumNegative(lst))

For the 2nd question, I'm a bit stuck on how to write it. 对于第二个问题,我对如何编写它有些困惑。 The question was: Count how many words occur in a list up to and including the first occurrence of the word “sap”. 问题是:计算一个列表中出现了多少个单词,直到并包括“ sap”单词的首次出现。 I'm assuming it's a random list but wasn't given much info so just going off that. 我假设这是一个随机列表,但没有得到太多信息,所以就不去讨论了。

I know the ending would be similar but no idea how the initial part would be since it's string opposed to numbers. 我知道结尾将是相似的,但不知道起始部分会如何,因为它是字符串,而不是数字。

I wrote a code for a in-class problem which was to count how many odd numbers are on a list(It was random list here, so assuming it's random for that question as well) and got: 我写了一个针对班级问题的代码,该代码用于计算列表中有多少个奇数(这里是随机列表,因此假设该问题也是随机的),得到:

import random

def countOdd(lst):
    odd = 0
    for e in lst:
        if e % 2 = 0:
            odd = odd + 1
    return odd

lst = []
for i in range(100):
    lst.append(random.randint(0, 1000))

print(countOdd(lst))

How exactly would I change this to fit the criteria for the 2nd question? 我将如何精确地更改它以适合第二个问题的标准? I'm just confused on that part. 我只是对此感到困惑。 Thanks. 谢谢。

The code to sum -ve numbers looks fine! 将-ve数字相加的代码看起来不错! I might suggest testing it on a list that you can manually check, such as: 我可能建议您在可以手动检查的列表上进行测试,例如:

print(sumNegative([1, -1, -2]))

The same logic would apply to your random list. 相同的逻辑将适用于您的随机列表。

A note about your countOdd function, it appears that you are missing an = ( == checks for equality, = is for assignment) and the code seems to count even numbers, not odd. 关于您的countOdd函数的注释,似乎您缺少了===检查是否相等, =是用于赋值),并且代码似乎在计算偶数而不是奇数。 The code should be: 代码应为:

def countOdd(lst):
    odd = 0
    for e in lst:
        if e%2 == 1:       # Odd%2 == 1
            odd = odd + 1
    return odd

As for your second question, you can use a very similar function: 至于第二个问题,您可以使用一个非常相似的函数:

def countWordsBeforeSap(inputList):
    numWords = 0
    for word in inputList:
        if word.lower() != "sap":      
            numWords = numWords + 1
        else:
            return numWords

inputList = ["trees", "produce", "sap"]
print(countWordsBeforeSap(inputList))

To explain the above, the countWordsBeforeSap function: 为了解释以上内容, countWordsBeforeSap函数:

  • Starts iterating through the words. 开始遍历单词。
  • If the word is anything other than "sap" it increments the counter and continues 如果单词不是"sap"它将增加计数器并继续
  • If the word IS "sap" then it returns early from the function 如果单词"sap"则它从函数中提前返回

The function could be more general by passing in the word that you wanted to check for: 通过输入您要检查的单词,该功能可以更通用:

def countWordsBefore(inputList, wordToCheckFor):
    numWords = 0
    for word in inputList:
        if word.lower() != wordToCheckFor:      
            numWords = numWords + 1
        else:
            return numWords

inputList = ["trees", "produce", "sap"]
print(countWordsBeforeSap(inputList, "sap"))

If the words that you are checking come from a single string then you would initially need to split the string into individual words like so: 如果您要检查的单词来自单个字符串,则首先需要将字符串split为单个单词,如下所示:

inputString = "Trees produce sap"
inputList   = inputString.split(" ")

Which splits the initial string into words that are separated by spaces. 它将初始字符串拆分为用空格分隔的单词。

Hope this helps! 希望这可以帮助! Tom 汤姆

def count_words(lst, end="sap"):
    """Note that I added an extra input parameter.
       This input parameter has a default value of "sap" which is the actual question.
       However you can change this input parameter to any other word if you want to by
       just doing "count_words(lst, "another_word".
    """
    words = []
    # First we need to loop through each item in the list.
    for item in lst:
        # We append the item to our "words" list first thing in this loop,
        # as this will make sure we will count up to and INCLUDING.
        words.append(item)

        # Now check if we have reached the 'end' word.
        if item == end:
            # Break out of the loop prematurely, as we have reached the end.
            break
    # Our 'words' list now has all the words up to and including the 'end' variable.
    # 'len' will return how many items there are in the list.
    return len(words)

lst = ["something", "another", "woo", "sap", "this_wont_be_counted"]
print(count_words(lst))

Hope this helps you understand lists better! 希望这可以帮助您更好地了解列表!

You can make effective use of list/generator comprehensions. 您可以有效地使用列表/生成器理解。 Below are fast and memory efficient. 以下是快速且高效存储的方法。

1. Sum of negatives: 1.负数之和:

print(sum( i<0 for i in lst))

2. Count of words before sap: Like you sample list, it assumes no numbers are there in list. 2. SAP之前的单词计数:就像您对列表进行采样一样,它假定列表中没有数字。

print(lst.index('sap'))

If it's a random list. 如果是随机列表。 Filter strings. 过滤字符串。 Find Index for sap 查找sap索引

l = ['a','b',1,2,'sap',3,'d']
l = filter(lambda x: type(x)==str, l)
print(l.index('sap'))

3. Count of odd numbers: 3.奇数计数:

print(sum(i%2 != 0 for i in lst))

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

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