此代码缺少什么?我试图使用.count()函数来获得总计,但我一直在获得0s

发布于 2025-01-24 01:54:56 字数 2287 浏览 0 评论 0原文

我正在使用.csv文件导入列表。现在已经编译了列表,我需要获得总计,并且我决定使用.count函数。列表名称是参与者[]。参与者列表中的每个条目都有100个条目: 与会者[姓名,状态,菜单_selection,fee_paid]

当我输入此代码时,我的总数等于0。我在编码方面非常新,并假设我缺少列出列表的东西。是否有人建议我如何将其适当地总计这些物品?这是所讨论的代码的一部分:

## Get Totals for each item in the attendee list.
def get_totals(attendees): 
        member = attendees.count('Member') #count of occurrences of members in attendees list
        print("~~~~~~~~~~~~~~~~~~~~~~~~")
        print(f"Total Members attending:        {member}")## display totals
        guest = attendees.count('Guest')   #count of occurrences of guests in attendees list
        print(f"Total Guests attending:         {guest}")## display totals
        child = attendees.count('Child')   #count of occurrences of children in attendees list
        print(f"Total Children attending:       {child}")## display totals
        print("======================================")
        fee_paid = 21
        total_attendees = member + guest + child
        print(f"Total Attendees:                {total_attendees}") ## display totals
        total_fees = total_attendees * fee_paid
        print(f"Total fees collected:           {total_fees}") ## display totals
        print("~~~~~~~~~~~~~~~~~~~~~~~~")
        chicken = attendees.count("Chicken")#count of occurrences of chicken in attendees list
        print(f"Total Chicken entrees:          {chicken}")## display totals
        beef = attendees.count("Beef")      #count of occurrences of beef in attendees list
        print(f"Total Beef entrees:             {beef}")## display totals
        veg = attendees.count("Vegetarian") #count of occurrences of vegetarian in attendees list
        print(f"Total Vegetarian entrees:       {veg}")## display totals
        print("~~~~~~~~~~~~~~~~~~~~~~~~")
        print()
        break

这是我在执行代码时看到的:

Command: total
~~~~~~~~~~~~~~~~~~~~~~~~
Total Members attending:        0
Total Guests attending:         0
Total Children attending:       0
======================================
Total Attendees:                0
Total fees collected:           0
~~~~~~~~~~~~~~~~~~~~~~~~
Total Chicken entrees:          0
Total Beef entrees:             0
Total Vegetarian entrees:       0
~~~~~~~~~~~~~~~~~~~~~~~~

有人可以提供帮助吗?

I am using a .csv file to import a list of lists. Now that the lists are compiled, I need to get totals and I've decided to use the .count function. The list name is attendees[]. There are 100 entries with the following items in each within the attendees list:
attendees[name, status, menu_selection, fee_paid]

When I enter this code, my totals all equal 0. I'm VERY new at coding and assume I'm missing something that will call the list. Does anyone have a suggestion as to how I can get this to properly total these items? Here is the portion of code in question:

## Get Totals for each item in the attendee list.
def get_totals(attendees): 
        member = attendees.count('Member') #count of occurrences of members in attendees list
        print("~~~~~~~~~~~~~~~~~~~~~~~~")
        print(f"Total Members attending:        {member}")## display totals
        guest = attendees.count('Guest')   #count of occurrences of guests in attendees list
        print(f"Total Guests attending:         {guest}")## display totals
        child = attendees.count('Child')   #count of occurrences of children in attendees list
        print(f"Total Children attending:       {child}")## display totals
        print("======================================")
        fee_paid = 21
        total_attendees = member + guest + child
        print(f"Total Attendees:                {total_attendees}") ## display totals
        total_fees = total_attendees * fee_paid
        print(f"Total fees collected:           {total_fees}") ## display totals
        print("~~~~~~~~~~~~~~~~~~~~~~~~")
        chicken = attendees.count("Chicken")#count of occurrences of chicken in attendees list
        print(f"Total Chicken entrees:          {chicken}")## display totals
        beef = attendees.count("Beef")      #count of occurrences of beef in attendees list
        print(f"Total Beef entrees:             {beef}")## display totals
        veg = attendees.count("Vegetarian") #count of occurrences of vegetarian in attendees list
        print(f"Total Vegetarian entrees:       {veg}")## display totals
        print("~~~~~~~~~~~~~~~~~~~~~~~~")
        print()
        break

This is what I'm seeing when the code is executed:

Command: total
~~~~~~~~~~~~~~~~~~~~~~~~
Total Members attending:        0
Total Guests attending:         0
Total Children attending:       0
======================================
Total Attendees:                0
Total fees collected:           0
~~~~~~~~~~~~~~~~~~~~~~~~
Total Chicken entrees:          0
Total Beef entrees:             0
Total Vegetarian entrees:       0
~~~~~~~~~~~~~~~~~~~~~~~~

Can anyone help?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我一向站在原地 2025-01-31 01:54:56

因此,首先澄清与会者项目,因此我们同意:这是每个项目尚存的项目列表另一个列表,其中包含name ,<代码>状态菜单> Selectionfee_paid

如果是这种情况,则与会者中的每个项目列表是列表SO none 它们将等于字符串“成员” (例如)。这就是为什么您的计数始终为零。

最好的选择是构建您 感兴趣的东西的列表并进行检查。对于的状态“成员”和菜单选择“ beef”,它会像以下内容一样:

def get_totals(attendees):
    # Get individual lists

    statuses = [item[1] for item in attendees]
    selections = [item[3] for item in attendees]

    member = statuses.count("Member")
    chicken = selections.count("Chicken")

说,我必须承认我是使用的忠实拥护者量身定制的数据结构(以及针对非平凡代码的键入提示),而不是库存列表和词典。这样做可以使这些工具可以拿走许多python疼痛点可以正确地完成工作(例如Pylintmypy)。

换句话说,类似的东西:

import dataclasses as dc
import typing as typ

@dc.dataclass
class Attendee:
    """ Specific data type for a single attendee, along
        with counting match functions as needed.
    """
    name: str
    status: str
    menu_selection: str
    fee_paid: float

    def status_match(self, check_list: typ.List[str]) -> int:
        """ Allows summation of attendees matching status.
        """
        return 1 if self.status in check_list else 0

    def menu_match(self, check_list: typ.List[str]) -> int:
        """ Allows summation of attendees matching menu selection.
        """
        return 1 if self.menu_selection in check_list else 0

@dc.dataclass
上课参加:
“”“参与者的列表类型,包括计数方法
在整个集合中。
”“”
与会者:typ.list [参与者]

def __init__(self):
    self.attendees = []

def add(self, item: Attendee) -> None
    self.attendees.append(item)

def count_status(self, statuses: typ_List[str]) -> int:
    return sum([item.status_match(statuses)
        for item in self.attendees])

def count_selection(self, selections: typ_List[str]) -> int:
    return sum([item.selection_match(selections)
        for item in self.attendees])

# And any other things such as deleting or enumerating.

然后,您将列表构建列表(取决于您如何阅读CSV数据):

attendees = AttendeeCollection()
for entry in get_csv_lines:
    attendees.add(Attendee(name=entry[0], status=entry[1],
        menu_selection=entry[2], fee_paid=entry[3]))

您要计算的代码,然后看起来更像是出于目的而编写的,而不是仅使用非常低- 级别的数据结构:

member = attendee_list.count_status(["Member"])
guest =  attendee_list.count_status(["Guest"])

chicken = attendee_list.count_selection(["Chicken"])
chicken_or_beef = attendee_list.count_selection((["Chicken", "Beef"])

现在,我并不建议您更改您的代码,只是现代Python提供的(但不是授权,这是一件好事)的方法来开发具有所有内容的软件C ++等静态定义的语言的优点。

So first clarifying the attendees item so we agree on that: This is a list of items where each item is yet another list containing, in order, name, status, menu_selection, and fee_paid.

If that's the case, each item in the attendees list is a list so none of them are going to be equal to the string "Member" (for example). That's why your count is always zero.

Your best bet is to construct a list of the things you are interested in and check that. For a status of "Member" and menu selection of "Beef", that would go something like:

def get_totals(attendees):
    # Get individual lists

    statuses = [item[1] for item in attendees]
    selections = [item[3] for item in attendees]

    member = statuses.count("Member")
    chicken = selections.count("Chicken")

Having said that, I must admit I'm a big fan of using tailored data structures (and type hinting) for non-trivial code, rather than the stock lists and dictionaries. Doing so allows the tools that take away a lot of Python pain points to do their job properly (things like pylint and mypy, for example).

In other words, something like this:

import dataclasses as dc
import typing as typ

@dc.dataclass
class Attendee:
    """ Specific data type for a single attendee, along
        with counting match functions as needed.
    """
    name: str
    status: str
    menu_selection: str
    fee_paid: float

    def status_match(self, check_list: typ.List[str]) -> int:
        """ Allows summation of attendees matching status.
        """
        return 1 if self.status in check_list else 0

    def menu_match(self, check_list: typ.List[str]) -> int:
        """ Allows summation of attendees matching menu selection.
        """
        return 1 if self.menu_selection in check_list else 0

@dc.dataclass
class AttendeeCollection:
""" List type for attendees, including count methods
across the entire collection.
"""
attendees: typ.List[Attendee]

def __init__(self):
    self.attendees = []

def add(self, item: Attendee) -> None
    self.attendees.append(item)

def count_status(self, statuses: typ_List[str]) -> int:
    return sum([item.status_match(statuses)
        for item in self.attendees])

def count_selection(self, selections: typ_List[str]) -> int:
    return sum([item.selection_match(selections)
        for item in self.attendees])

# And any other things such as deleting or enumerating.

Then you construct the list with something like (depending on how you're reading the CSV data):

attendees = AttendeeCollection()
for entry in get_csv_lines:
    attendees.add(Attendee(name=entry[0], status=entry[1],
        menu_selection=entry[2], fee_paid=entry[3]))

And your code to count things then looks more like it was written for purpose rather than just using very low-level data structures:

member = attendee_list.count_status(["Member"])
guest =  attendee_list.count_status(["Guest"])

chicken = attendee_list.count_selection(["Chicken"])
chicken_or_beef = attendee_list.count_selection((["Chicken", "Beef"])

Now I'm not suggesting you should change your code to that, just that modern Python provides (but does not mandate, which is a good thing) ways to develop software that have all the advantages of statically defined languages like C++.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文