【问题标题】:Problem with sorted phone numbers from hackerrank从hackerrank排序电话号码的问题
【发布时间】:2022-01-09 23:48:41
【问题描述】:

我知道我的尝试非常基础,我对 python 的了解也是如此。 该问题要求从用户那里获取多个数字,并从其左侧删除可能的 0、+91 或 91,使其成为 10 位数字,然后对其进行排序和打印。

我试过num_list[1] = num_list[1][len(num_list[1])-10:]。它有效,所以我尝试将它放在我正在学习的列表理解格式中,但它当时不起作用。我需要有关如何做到这一点的帮助,希望能更好地了解何时应该使用理解格式。

n = int(input()) # get number of phone numbers from user
num_list = [] # an empty list to store phone numbers in
num_list = [input() for _ in range(n)] # store phone numbers in num_list
##################################
num_list = [num_list[num] = num_list[num][len(num_list[num])-10:] for num in num_list]  #remove  possible 0, +91, 91 from beginning of numbers
########################################
num_list = sorted(num_list)
num_list = ["+91 "+num[:5]+" "+num[5:] for num in num_list]
print(*num_list , sep="\n")

【问题讨论】:

  • 列表推导评估一个表达式,将所有结果放入一个列表中。赋值语句num_list[num] = num_list[num][len(num_list[num])-10:] 不是表达式,而是语句。
  • 对于切片表示法,len(num_list[num]) 是多余的 - 当您使用负索引时,Python 会自动添加它。

标签: python python-3.x function list-comprehension


【解决方案1】:

您不应该直接在列表推导中赋值。

您要查找的语法是:

num_list = [num[-10:] for num in num_list]

逻辑上等价于:

cleaned_list = []
for num in num_list:
    cleaned_list.append(num[-10:])
num_list = cleaned_list

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    • 1970-01-01
    • 2016-04-15
    相关资源
    最近更新 更多