You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何对print输出的电话号码投票结果按号码分组排序?

解决方案:先存储数据,再分组排序输出

你遇到的问题核心是直接打印输出的内容没法再进行排序分组操作,因为print是直接输出到控制台的,没有返回值也不能像文件那样读行。正确的思路是先把生成的所有投票记录存储起来,之后再按前缀分组、排序,最后统一输出。

下面是修改后的代码,我还顺便修正了原代码里的两个小问题:

  • 字符串比较用==而不是is(is是比较对象身份,字符串比较推荐用==)
  • 德国的weights列表多了一个元素,已经调整为和国家数量匹配:
import random

Countries = ["Belgium", "Netherlands", "Italy", "France", "Germany", "Spain"]
# 用字典存储分组,键是电话号码前缀,值是该前缀下的投票记录列表
vote_records = {}

for num in range(5):
    country = random.choice(Countries)
    phone = ""
    countryVote = ""
    
    if country == "Belgium":
        phone = f'+32 4{random.randint(1000, 9999)}-{random.randint(1000,9999)}'
        countryVote = random.choices(Countries, weights=[0, 25, 7, 25, 25, 7], k=1)[0]  # 取出列表里的单个元素
    elif country == "Netherlands":
        phone = f'+31 6{random.randint(1000, 9999)}-{random.randint(1000,9999)}'
        countryVote = random.choices(Countries, weights=[25, 0, 5, 15, 20, 8], k=1)[0]
    elif country == "Italy":
        phone = f'+39 3{random.randint(1000, 9999)}-{random.randint(1000,9999)}'
        countryVote = random.choices(Countries, weights=[5, 5, 0, 20, 5, 13], k=1)[0]
    elif country == "France":
        phone = f'+33 1{random.randint(1000, 9999)}-{random.randint(1000,9999)}'
        countryVote = random.choices(Countries, weights=[15, 8, 10, 0, 12, 8], k=1)[0]
    elif country == "Germany":
        phone = f'+49 1{random.randint(1000, 9999)}-{random.randint(1000,9999)}'
        countryVote = random.choices(Countries, weights=[8, 8, 9, 5, 0, 12], k=1)[0]  # 修正weights长度
    elif country == "Spain":
        phone = f'+34 6{random.randint(1000, 9999)}-{random.randint(1000,9999)}'
        countryVote = random.choices(Countries, weights=[5, 5, 15, 15, 10, 0], k=1)[0]
    else:
        phone = f'Country does not exist'
        countryVote = random.choice(Countries)
    
    # 提取电话号码前缀(比如+31)
    prefix = phone.split()[0]
    # 如果前缀不在字典里,先创建空列表
    if prefix not in vote_records:
        vote_records[prefix] = []
    # 添加当前记录到对应前缀的列表
    vote_records[prefix].append(f'{phone} voted for {countryVote}')

# 按前缀排序,然后输出每组内容
for prefix in sorted(vote_records.keys()):
    print(f'--- {prefix} ---')
    for record in vote_records[prefix]:
        print(record)

代码说明:

  • 存储数据:用vote_records字典来分组,键是电话号码前缀,值是该前缀下的所有投票记录,这样能轻松把相同前缀的记录归到一起。
  • 提取前缀:通过phone.split()[0]把电话号码按空格拆分,取第一个元素就是前缀(比如+31)。
  • 排序输出:用sorted(vote_records.keys())对前缀进行排序,然后逐个输出每组的标题和记录,这样结果就是按前缀有序分组的了。

这样修改后,你就能得到按电话号码前缀分组排序后的输出,而不是零散的打印结果啦。

内容的提问来源于stack exchange,提问作者Suduwudu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:16:25