我想从一个数字列表中随机创建5个由5个数字组成的列表。
import random
def team():
x = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
y = []
Count = 0
count = 0
while Count < 5:
while count<5:
count += 1
z = random.choice(x)
y += z
x.remove(z)
print(y)
Count +=1
team()
我想要5组不重复的数字
答案 0 :(得分:1)
将代码更改为
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { AppError } from '../common/validators/app-error';
import { NotFoundError } from '../common/not-found-error';
import { BadRequest } from './../common/bad-request-error';
export class DataService {
constructor(private url: string, private httpClient: HttpClient) {
}
getAll(){
return this.httpClient.get(this.url).pipe(catchError(this.handleError));
}
getOne(ressource){
return this.httpClient.get(this.url + '/' + ressource).pipe(catchError(this.handleError));
}
create(ressource){
return this.httpClient.post(this.url, JSON.stringify(ressource)).pipe(catchError(this.handleError));
}
update(ressource,oldRessource){
return this.httpClient.put(this.url + '/' + oldRessource, JSON.stringify(ressource)).pipe(catchError(this.handleError));
}
delete(ressource){
return this.httpClient.delete(this.url + '/' + ressource).pipe(catchError(this.handleError));
}
public handleError(err: Response){
if (err.status == 400 ){
return Observable.throw(new BadRequest(err));
}
if (err.status == 404) {
return Observable.throw(new NotFoundError());
}
// Return error by default if no specific error
return Observable.throw(new AppError(err));
}
}
实际上,对于您的原始代码,import random
def team():
Count = 0
while Count < 5:
x = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
y = []
count = 0
while count<5:
count += 1
z = random.choice(x)
y += z
x.remove(z)
print(y)
Count +=1
team()
变为count
并中断了第二个for循环。但是下一次,您的5
仍然是count
,因此它不会进入第二个for循环。
您刚5
第一次获得print
五次五次::)
答案 1 :(得分:1)
如果您使用嵌套列表推导,这是一个单行代码。同样,我们可以直接对整数0..9进行采样,而不是对字符串['0', '1',...,'9']
import random
teams = [[random.randrange(10) for element in range(5)] for count in range(5)]
# Here's one example run: [[0, 8, 5, 6, 2], [6, 7, 8, 6, 6], [8, 8, 6, 2, 2], [0, 1, 3, 5, 8], [7, 9, 4, 9, 6]]
或者如果您真的要输出字符串而不是整数:
teams = [[str(random.randrange(10)) for element in range(5)] for count in range(5)]
[['3', '8', '2', '5', '3'], ['7', '1', '9', '7', '9'], ['4', '8', '0', '4', '1'], ['7', '6', '5', '8', '2'], ['6', '9', '2', '7', '3']]
或者如果您真的想要随机采样任意字符串列表:
[ random.sample(['0','1','2','3','4','5','6','7','8','9'], 5) for count in range(5) ]
[['7', '1', '5', '3', '0'], ['7', '1', '6', '2', '8'], ['3', '0', '9', '7', '2'], ['5', '1', '7', '3', '2'], ['6', '2', '5', '0', '3']]