【问题标题】:Finding the lowest number that does not occur at the end of a string, in a tuple in a list在列表的元组中查找未出现在字符串末尾的最小数字
【发布时间】:2021-01-27 05:15:51
【问题描述】:

我有一个元组列表,每个元组都有一个字符串作为元素 0,我想在这些字符串中取出最终数字,然后找到不在此列表中的最小(正)数。

你是怎么做到的?

例如对于列表tups

tups=[('.p1.r1.c2',),('.p1.r1.c4',),('.p1.r1.c16',)]

最后的数字是2416,所以最小的未使用数字是1


我的尝试是这样的:

tups2= [tup[0] for tup in tups]         # convert tuples in lists to the strings with information we are interested in
tups3 = [tup .rfind("c") for tup in tups2] # find the bit we care about

我不确定如何完成它,或者它是否是快速/智能的方式

【问题讨论】:

  • 到目前为止你尝试过什么?您能否分享您编写的代码,并准确指出什么不起作用,错误是什么?
  • 我已经完成了您要求的更改

标签: python tuples


【解决方案1】:

你在哪里被屏蔽了?您可以通过两个步骤来实现:

第 1 步:创建数字列表

这样做的一种方式(灵感来自there):

numbers = [int(s[0][len(s[0].rstrip('0123456789')):]) for s in tups]

在您的示例中,numbers[2, 4, 16]

第 2 步:找出不在此列表中的最小正数

x = 1
while x in numbers:
  x += 1

【讨论】:

    【解决方案2】:

    您并没有真正说明您的问题,但我猜想获得最低的未使用数字是问题所在。 上面的解决方案很棒,但它只是获得列表中最低的数字,而不是最低的未使用数字。 我试图列出所有未使用的数字,然后得到它的最小值。

    希望对你有帮助

    tups=[('15.p1.r1.c2',),('.poj1.r1.c4',),('.p2.r4.c160',)]
    numbers = []
    unused_numbers = []
    for tup in tups:
        words = tup[0].strip(".").split('.')
        digits_list = [''.join(x for x in i if x.isdigit()) for i in words]
        unused_numbers.extend(digits_list[:-1])
        numbers.append(digits_list[-1])
    print(numbers)
    print(min(unused_numbers))
    

    【讨论】:

      【解决方案3】:

      我使用了 Thibault D 用来获取数字列表的相同方法:

      tups=[('.p1.r1.c2',),('.p1.r1.c4',),('.p1.r1.c16',)]
      num = [int(i[0][len(i[0].rstrip('0123456789')):]) for i in tups]
      

      但是,我使用了一种更简单的方法来获得最小数量:

      min(num) - 1
      

      这基本上是获取列表中最小的数字,然后从中减去 1。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多