添加到空集

时间:2015-05-19 19:31:27

标签: python

empty_set = set()

我如何使用循环将10个随机整数(从10到30)添加到上面的空集中?

另外,我如何使用另一个循环来处理集合,该集合在一行上显示集合的所有元素,由**分隔,并计算有多少元素是偶数,多少元素是奇数,然后显示计数?

尝试输出类似下面的内容:

12**16**17**18**20**21**22**23**24**28**
Set has 7 even numbers and 3 odd numbers

从heinst帮助我的方面来看,我正在尝试将列表更改为一组......这是对的吗?

import random



numbers = set()
for _ in range(0, 10):
numbers.add(random.randrange(10, 30))
printStr = ''
evens = 0
odds = 0
for num in numbers:
printStr += '{0}**'.format(num)
if num % 2 == 0:
    evens += 1
else:
    odds += 1

print (printStr)

print ('Set has {0} even numbers and {1} odd numbers'.format(evens, odds))

1 个答案:

答案 0 :(得分:2)

我真的建议您坐下来阅读Python,但这就是我解决问题的方法。我添加了评论来解释每一行。

import random

#list comprehension, but since you are new use uncommented  way
#numbers = [random.randrange(10, 30) for i in range(0, 10)]

#creates an empty list
numbers = []
#goes from 0 - 9, _ means no variable necessary, just looping a set number of times
for _ in range(0, 10):
    #generates a random number from 10 - 30 and appends it to the numbers list
    numbers.append(random.randrange(10, 30))

#creates an empty string and num of evens and odds at 0
printStr = ''
evens = 0
odds = 0
#for each number in numbers list
for num in numbers:
    #add to print string with number and two asterisks after it
    printStr += '{0}**'.format(num)
    #check if its even, if so increment even count
    if num % 2 == 0:
        evens += 1
    #if not, increment odd count
    else:
        odds += 1
#print string of all numbers and 2 asterisks after each number
print printStr
#print that the list has x evens and x odds
print 'List has {0} even numbers and {1} odd numbers'.format(evens, odds)