如何在python中将集合转换为整数?

时间:2017-04-12 04:40:19

标签: python python-3.x

我想生成一个随机的4位数字,其中没有任何数字重复。

 import random

 sets = random.sample(range(0,9), 4)

这会生成一个4位数的随机集,但我希望它是一个整数。我怎么做?

7 个答案:

答案 0 :(得分:3)

(假设OP表示所有数字)
不要使用数字而必须操纵str并返回int,只需从ascii数字开始:

>>> import string
>>> ''.join(random.sample(string.digits, 4))
'4561'

如有必要,您可以转换为int() 如果第一个数字是0,则不清楚OP打算做什么。

对于纯数值方法,您可以使用functools.reduce

>>> import functools as ft
>>> ft.reduce(lambda s, d: 10*s + d, random.sample(range(10), 4))
2945

答案 1 :(得分:1)

您可以通过将每个数字转换为字符串,连接它们并将它们转换为整数来完成此操作。

Scanner

答案 2 :(得分:1)

如果您需要生成4位数字,仅供知识目的使用。

根据AChampion的建议,此解决方案可以包含重复项

  
    
      

来自随机导入randint       兰丁(1000,9999)

    
  

使用bernie Solution生成一个随机的4位数字,其中不会重复任何数字。

int("".join(map(str,random.sample(range(0,9),4))))

答案 3 :(得分:1)

如果您想要具有4个唯一数字的潜在无限数字序列(或任何其他条件 - 编写您自己的数字)

    public static XDocument ConvertCsvToXml(string sourcePath)
    {
        string[] lines;

        try
        {
            lines = File.ReadAllLines(sourcePath);
        }
        catch (Exception e)
        {
            System.Diagnostics.Debug.WriteLine(e.Message);
            return null;
        }

        var headers = lines[0].Split(';').Select(x => x.Trim('\"')).ToArray();

        var xml = new XElement("FullInvoice", lines.Where((line, index) => index > 0)
           .Select(line => new XElement("Line", line.Split(';')
           .Select((column, index) => new XElement(headers[index], column)))));

        return new XDocument(xml);
    }

仅适用于Python 3,因为filter返回iterator-object(在Python 2.7中返回import random def numbers_gen(left_end, right_end): while True: yield random.randint(left_end, right_end) def are_digits_unique(number): number_string = str(number) return list(set(number_string)) == list(number_string) four_digits_numbers_gen = number_gen(left_end=1000, right_end=9999) four_digits_numbers_with_unique_digits_gen = filter(are_digits_unique, four_digits_numbers_gen) ,更多返回docs

答案 4 :(得分:0)

你可以乘以10的幂:

sum(10**a*b for a, b in enumerate(reversed(sets)))

只要sets的第一个元素不为零,就可以正常工作。

答案 5 :(得分:0)

你可以尝试:

import random
my_set = set()
while len(my_set) < 4:
    x = random.choice(range(0,9))
    my_set.add(x)
my_num = int("".join(map(str, my_set)))

答案 6 :(得分:0)

一行:

int("".join(random.sample("0123456789",4)))
相关问题