我想调查研究python 3.7的os.urandom()函数代码。我查看了各自的标准库的os.py,但它既没有在那里定义,也没有在那里导入。我也尝试 grep 定义:
/usr/lib/python3.7 $ grep -rFl "def urandom" 2> /dev/null
但没什么。我怀疑 os.urandom() 发生了一些神奇的事情。在哪里可以找到用于学习和密码分析的函数定义?
这是一个元编程问题:我想了解为什么python开发人员在new中引入了另一个运算符:=。我知道这是干什么的 但是,我想知道为什么开发人员选择一个新的符号而不是重复使用例如as运算符。
即为什么认为最好写
while (command := input("> ")) != "quit":
print("You entered:", command)
Run Code Online (Sandbox Code Playgroud)
而不是
while input("> ") as command != "quit":
print("You entered:", command)
Run Code Online (Sandbox Code Playgroud) python language-design python-3.x python-3.8 python-assignment-expression
在我目前正在使用python3开发的应用程序中,我经常使用类似的语句
elem_in_list = elem in list
Run Code Online (Sandbox Code Playgroud)
但有时我需要检查元素是否不在列表中.是否有性能差异
elem_not_in_list = not elem in list
Run Code Online (Sandbox Code Playgroud)
和
elem_not_in_list = elem not in list
Run Code Online (Sandbox Code Playgroud)
还是一样的?其中一个符号更可取吗?
我有发电机像
def not_nones(some_iterable):
for item in some_iterable:
if item is not None:
yield item
Run Code Online (Sandbox Code Playgroud)
但由于"扁平比嵌套好",我想在一行中做到这一点,如:
def not_nones(some_iterable):
for item in some_iterable:
yield item if item is not None else None
Run Code Online (Sandbox Code Playgroud)
但这实际上会None成为发电机的一个项目.是否有可能在单行中不产生任何东西?
我有时使用生成器来过滤程序中的某些值,并希望记录过滤的项目.
我们假设:
def filter_items(items):
for item in items:
if item.is_wanted():
yield item
def process_items(items):
for item in filter_items(items):
item.do_stuff()
Run Code Online (Sandbox Code Playgroud)
现在我的问题是我想记录,实际调用了多少过滤的项目.
目前我这样做:
def process_items(items):
for count, item in enumerate(filter_items(items)):
item.do_stuff()
try:
count += 1
except UnboundLocalError:
count = 0
print('Processed', count, 'items.')
Run Code Online (Sandbox Code Playgroud)
现在我有这样的感觉,检查UnboundLocalError一个有点奇怪,所以我考虑默认计数器:
def process_items(items):
count = -1
for count, item in enumerate(filter_items(items)):
item.do_stuff()
print('Processed', count + 1, 'items.')
Run Code Online (Sandbox Code Playgroud)
然而,设置默认计数器-1也看起来很奇怪,因为没有迭代的实际默认值将是0.但是我不能默认它,0因为我无法区分默认值(如果没有迭代元素)或者是否迭代了一个元素.
有关Python中循环计数器默认的最佳实践或指南吗?
我想要一个Vec<CustomType>可以加入的&str。这是我到目前为止所尝试过的:
#[derive(Debug)]
struct Item {
string: String,
}
impl Item {
pub fn new(string: impl Into<String>) -> Self {
Self {
string: string.into(),
}
}
pub fn to_string(&self) -> &String {
&self.string
}
}
impl From<&Item> for &String {
fn from(item: &Item) -> Self {
&item.string
}
}
impl From<&Item> for &str {
fn from(item: &Item) -> Self {
&item.string.to_string()
}
}
fn main() {
let items = Vec::from([Item::new("Hello"), Item::new("world")]);
let string = items.join(" ");
println!("{}", …Run Code Online (Sandbox Code Playgroud) 我有这个代码
use std::iter::Step;
fn main() {
for i in mkiter(25, 20) {
println!("{}", i);
}
for i in mkiter(10, 23) {
println!("{}", i);
}
}
fn mkiter<T>(start: T, end: T) -> Box<dyn Iterator<Item = T>>
where
T: Step,
{
if start > end {
Box::new((end..=start).rev())
} else {
Box::new(start..=end)
}
}
Run Code Online (Sandbox Code Playgroud)
但是,编译器告诉我我正在使用不稳定的功能:
error[E0658]: use of unstable library feature 'step_trait': recently redesigned
--> main.rs:1:5
|
1 | use std::iter::Step;
| ^^^^^^^^^^^^^^^
|
= note: see issue #42168 <https://github.com/rust-lang/rust/issues/42168> for more information …Run Code Online (Sandbox Code Playgroud) 我有一些这样的代码:
type MyResult = Result<u8, String>;
fn main() {
match check(42) {
Ok(number) => println!("OK: {}", number),
Err(msg) => println!("Error: {}", msg),
}
match check(1337) {
Ok(number) => println!("OK: {}", number),
Err(msg) => println!("Error: {}", msg),
}
}
fn check(number: i32) -> MyResult {
if (0..256).contains(&number) {
Ok(number as u8)
} else {
Err("Out of bounds!".to_string())
}
}
Run Code Online (Sandbox Code Playgroud)
是否可以通过访问 的魔术成员或方法来获取此类型,而不是u8在 中再次显式指定?我基本上是在寻找类似的东西:check()MyResult
fn check(number: i32) -> MyResult {
if (0..256).contains(&number) {
Ok(number as MyResult::ok_type())
} else { …Run Code Online (Sandbox Code Playgroud) 我已经使用clap.
在其中,我有几个结构体和枚举,其中包含特定子命令的这些结构体。
我现在遇到了某种类型的代码重复问题,想知道 Rust 语言是否有一些我不知道的功能可以消除重复。
这是一个 MRE:
pub trait Runner {
fn run(&self);
}
pub struct Foo;
impl Runner for Foo {
fn run(&self) {
println!("Fooing");
}
}
pub struct Bar;
impl Runner for Bar {
fn run(&self) {
println!("Baring");
}
}
pub enum Action {
DoFoo(Foo),
DoBar(Bar),
}
impl Runner for Action {
fn run(&self) {
match self {
Self::DoFoo(runner) => runner.run(),
Self::DoBar(runner) => runner.run(),
}
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,模式匹配<Action as Runner>::run()在所有变体上都具有几乎相同的代码,因为所有枚举变体的元组都包含一个实现Runner.
在这个 …