以下是我认为应该如何工作的:
dictionary = {'k1': {'a': 'b'}, 'k2': [0, 1]}
pointer = dictionary['k1']
print pointer
>>> {'a': 'b'}
pointer.update({'a': 'c'})
print dictionary
>>> {'k1': {'a': 'c'}, 'k2': [0, 1]}
Run Code Online (Sandbox Code Playgroud)
以下内容让我感到沮丧:
pointer = dictionary['k2']
print pointer
>>> [0, 1]
pointer.update([2, 3])
>>> AttributeError: 'list' object has no attribute 'update'
Run Code Online (Sandbox Code Playgroud)
我知道 list 没有更新功能,并且知道我可以执行以下操作:
pointer[0] = 2
Run Code Online (Sandbox Code Playgroud)
...但我想要一个更通用的选项来更新参考值,因此该对象仍然属于字典,但值已更改。
这样做的原因是我有一个嵌套的字典,看起来像:
dictionary['key']['key']['key']['key']
Run Code Online (Sandbox Code Playgroud)
我的问题不是针对列表是否具有更新功能——而是我问的是是否有一种更简洁的方法来引用和更改深度嵌套字典中的值,以便将其存储在参考值中会更好而不是每次我想给它分配一些东西时都把它全部打出来。
谢谢!
编辑:第一个示例中的固定语法
EDIT2:让我说清楚:我知道列表没有update函数,而是询问通用参考值更新
EDIT3:简化问题
我不理解Python中列表的以下异常行为,如果有人可以抛出一些亮点,我会很感激:
小片1:
myList = [1,2,3,4]
A = [myList]*3
print(A)
myList[2]=45
print(A)
Run Code Online (Sandbox Code Playgroud)
输出:
[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
[[1, 2, 45, 4], [1, 2, 45, 4], [1, 2, 45, 4]]
Run Code Online (Sandbox Code Playgroud)
这对我来说很有意义,因为我们没有执行额外的复制功能来"屏蔽"A对myList上的元素操作.
摘录2:
myList = [1,2,3,4]
A = myList*3
print(A)
myList[2]=45
print(A)
Run Code Online (Sandbox Code Playgroud)
输出:
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)
为什么对myList的更改未反映在A中?
我不明白MutexGuard内部代码块中的"where" .互斥锁被锁定和解开,产生一个MutexGuard.不知何故,这段代码设法取消引用,MutexGuard然后可变地借用该对象.MutexGuard去哪儿了?而且,令人困惑的是,这种解除引用不能被替换deref_mut.为什么?
use std::sync::Mutex;
fn main() {
let x = Mutex::new(Vec::new());
{
let y: &mut Vec<_> = &mut *x.lock().unwrap();
y.push(3);
println!("{:?}, {:?}", x, y);
}
let z = &mut *x.lock().unwrap();
println!("{:?}, {:?}", x, z);
}
Run Code Online (Sandbox Code Playgroud) 我在Rust中为简单的结构编写了以下代码。这只是一个例子,没有太多真实的逻辑:
struct Vec2 {
x: f32,
y: f32,
}
impl Vec2 {
fn multiply(&mut self, other: &Vec2) {
self.x *= other.x;
self.y *= other.y;
}
}
Run Code Online (Sandbox Code Playgroud)
我可以创建简单的向量,然后将向量与另一个向量相乘,但是当我尝试将向量与自身向量相乘时遇到了一个问题:编译器抱怨我不能借用该向量,因为它也被借为不可变的。
fn main() {
let mut vec = Vec2 { x: 2.0, y: 2.3 };
vec.multiply(&vec);
}
Run Code Online (Sandbox Code Playgroud)
struct Vec2 {
x: f32,
y: f32,
}
impl Vec2 {
fn multiply(&mut self, other: &Vec2) {
self.x *= other.x;
self.y *= other.y;
}
}
Run Code Online (Sandbox Code Playgroud)
这是有道理的,但是将这样的向量与其自身相乘的正确方法是什么?更重要的是:对于一般情况,我需要使用自己的方法(使用与参数相同的结构)来修改结构。
我有一个Vec结构体。Vec当使用迭代时,.iter()我想编辑for循环内的每个元素,但我收到一个错误,指出每个元素已被借用,我该如何解决这个问题?这是一个小代码示例:
struct complex_struct {
attr1: i32
}
let elements: Vec<complex_struct> = generate_data();
for element in elements.iter() {
element.attr1 = 0;
}
Run Code Online (Sandbox Code Playgroud) 游戏的最小示例,玩家拥有一个位置并随着时间的流逝而走动。编译如下:
use std::thread::sleep;
use std::time::Duration;
struct Player {
position: usize,
}
impl Player {
fn new() -> Self {
Self { position: 0 }
}
}
impl Player {
fn get_position(&self) -> usize {
self.position
}
}
impl Player {
fn walk(&mut self) {
self.position += 1;
}
}
fn main() {
let mut player = Player::new();
loop {
player.walk();
sleep(Duration::from_secs(1));
}
}
Run Code Online (Sandbox Code Playgroud)
如果玩家借用该位置而不是拥有它,则不会编译:
use std::thread::sleep;
use std::time::Duration;
struct Player<'a> {
position: &'a mut usize,
}
impl<'a> Player<'a> {
fn …Run Code Online (Sandbox Code Playgroud) 你为什么要申报IEnumerable<T> readonly?
从这篇关于异步和等待的文章中我们得到以下代码.
class OrderHandler
{
private readonly IEnumerable<Order> _orders;
public OrderHandler()
{
// Set orders.
}
public IEnumerable<Order> GetAllOrders()
{
return _orders;
}
}
Run Code Online (Sandbox Code Playgroud)
IEnumerable<T>是不可改变的.这与readonly关键字有何不同?
我现在已经在这里停留了一段时间,无法弄清楚如何让这个领域变得word可变.有人可以在这里指出我的问题.
pub struct Person<'name>{
name:&'name Name
}
pub struct Name{
word: String
}
impl<'name> Person<'name>{
pub fn new(name:&'name mut Name)-> Person<'name>{
Person {
name: name
}
}
}
fn main(){
let mut name: Name = Name {
word: String::from("Petre")
};
let mut person: Person = Person::new(&mut name);
first(&mut person);
}
pub fn first(person:&mut Person){
person.name.word = String::from("Wurst");
second(person);
}
pub fn second(person:&mut Person){
println!("{}",person.name.word)
}
Run Code Online (Sandbox Code Playgroud)
产量
Run Code Online (Sandbox Code Playgroud)error: cannot assign to immutable field `person.name.word` --> main.rs:27:5 | 27 | …
我有这段代码,我尝试将命令行参数转换为整数.问题是,变量width和height应该是不可变的,因为我不打算改变它们.有没有什么方法可以使用匹配let width = {match....},并在一个步骤中将它们初始化为不可变变量,而不是给它们一个默认值并改变它们?我相信这会更安全,更有效率.
let args: Vec<String> = env::args().collect();
let width_arg = &args[1];
let height_arg = &args[2];
let mut width = 0;
let mut height = 0;
match width_arg.parse::<i32>() {
Ok(w) => width = w,
Err(_) => ask_for_number(),
}
match height_arg.parse::<i32>() {
Ok(h) => height = h,
Err(_) => ask_for_number(),
}
Run Code Online (Sandbox Code Playgroud) 我想解决Rust中的leetcode问题(从列表末尾删除第N个节点).我的解决方案使用两个指针来查找Node要删除的内容:
#[derive(PartialEq, Eq, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>,
}
impl ListNode {
#[inline]
fn new(val: i32) -> Self {
ListNode { next: None, val }
}
}
// two-pointer sliding window
impl Solution {
pub fn remove_nth_from_end(head: Option<Box<ListNode>>, n: i32) -> Option<Box<ListNode>> {
let mut dummy_head = Some(Box::new(ListNode { val: 0, next: head }));
let mut start = dummy_head.as_ref();
let mut end = dummy_head.as_ref();
for _ in 0..n {
end …Run Code Online (Sandbox Code Playgroud) mutability ×10
rust ×7
immutability ×3
python ×2
c# ×1
dictionary ×1
element ×1
ienumerable ×1
iterator ×1
list ×1
methods ×1
mutex ×1
pointers ×1
readonly ×1
reference ×1
struct ×1
variables ×1
vector ×1