1619697780
In the last post I created a React component that intercepted and formatted the arguments for console.log
and console.error
.
In this post I’ll be upgrading from a simple <textarea>
to something that is designed to show code.
After mulling over a few different options, even considering making something from scratch, I decided that CodeMirror would be the best fit for short code snippets.
Fortunately, CodeMirror v6 is out and it’s a fantastic opportunity to try it out.
The editor component will live in src/components/editor/index.tsx
. For now, it will be an empty react component.
import React from "react";
export const Editor = () => {
return <></>;
};
We’ll also need to install some libraries from npm
npm i @codemirror/view @codemirror/state
CodeMirror needs to be attached to a DOM node, so we’ll add it via a ref
. We’ll also use a <section>
for some added semantics. In the world of TypeScript types, I learned that any HTML element that doesn’t need more than what the base interface provides, like <section>
, should use the HTMLElement
type.
import React from "react";
export const Editor = () => {
const editorRef = React.useRef<HTMLElement>(null);
return <section ref="editorRef"/>;
};
#react #codemirror #typescript #typescript-with-react
1635917640
このモジュールでは、Rustでハッシュマップ複合データ型を操作する方法について説明します。ハッシュマップのようなコレクション内のデータを反復処理するループ式を実装する方法を学びます。演習として、要求された注文をループし、条件をテストし、さまざまなタイプのデータを処理することによって車を作成するRustプログラムを作成します。
錆遊び場は錆コンパイラにブラウザインタフェースです。言語をローカルにインストールする前、またはコンパイラが利用できない場合は、Playgroundを使用してRustコードの記述を試すことができます。このコース全体を通して、サンプルコードと演習へのPlaygroundリンクを提供します。現時点でRustツールチェーンを使用できない場合でも、コードを操作できます。
Rust Playgroundで実行されるすべてのコードは、ローカルの開発環境でコンパイルして実行することもできます。コンピューターからRustコンパイラーと対話することを躊躇しないでください。Rust Playgroundの詳細については、What isRust?をご覧ください。モジュール。
このモジュールでは、次のことを行います。
Rustのもう1つの一般的なコレクションの種類は、ハッシュマップです。このHashMap<K, V>
型は、各キーK
をその値にマッピングすることによってデータを格納しますV
。ベクトル内のデータは整数インデックスを使用してアクセスされますが、ハッシュマップ内のデータはキーを使用してアクセスされます。
ハッシュマップタイプは、オブジェクト、ハッシュテーブル、辞書などのデータ項目の多くのプログラミング言語で使用されます。
ベクトルのように、ハッシュマップは拡張可能です。データはヒープに格納され、ハッシュマップアイテムへのアクセスは実行時にチェックされます。
次の例では、書評を追跡するためのハッシュマップを定義しています。ハッシュマップキーは本の名前であり、値は読者のレビューです。
use std::collections::HashMap;
let mut reviews: HashMap<String, String> = HashMap::new();
reviews.insert(String::from("Ancient Roman History"), String::from("Very accurate."));
reviews.insert(String::from("Cooking with Rhubarb"), String::from("Sweet recipes."));
reviews.insert(String::from("Programming in Rust"), String::from("Great examples."));
このコードをさらに詳しく調べてみましょう。最初の行に、新しいタイプの構文が表示されます。
use std::collections::HashMap;
このuse
コマンドは、Rust標準ライブラリの一部HashMap
からの定義をcollections
プログラムのスコープに取り込みます。この構文は、他のプログラミング言語がインポートと呼ぶものと似ています。
HashMap::new
メソッドを使用して空のハッシュマップを作成します。reviews
必要に応じてキーと値を追加または削除できるように、変数を可変として宣言します。この例では、ハッシュマップのキーと値の両方がString
タイプを使用しています。
let mut reviews: HashMap<String, String> = HashMap::new();
このinsert(<key>, <value>)
メソッドを使用して、ハッシュマップに要素を追加します。コードでは、構文は<hash_map_name>.insert()
次のとおりです。
reviews.insert(String::from("Ancient Roman History"), String::from("Very accurate."));
ハッシュマップにデータを追加した後、get(<key>)
メソッドを使用してキーの特定の値を取得できます。
// Look for a specific review
let book: &str = "Programming in Rust";
println!("\nReview for \'{}\': {:?}", book, reviews.get(book));
出力は次のとおりです。
Review for 'Programming in Rust': Some("Great examples.")
ノート
出力には、書評が単なる「すばらしい例」ではなく「Some( "すばらしい例。")」として表示されていることに注意してください。get
メソッドはOption<&Value>
型を返すため、Rustはメソッド呼び出しの結果を「Some()」表記でラップします。
この.remove()
メソッドを使用して、ハッシュマップからエントリを削除できます。get
無効なハッシュマップキーに対してメソッドを使用すると、get
メソッドは「なし」を返します。
// Remove book review
let obsolete: &str = "Ancient Roman History";
println!("\n'{}\' removed.", obsolete);
reviews.remove(obsolete);
// Confirm book review removed
println!("\nReview for \'{}\': {:?}", obsolete, reviews.get(obsolete));
出力は次のとおりです。
'Ancient Roman History' removed.
Review for 'Ancient Roman History': None
このコードを試して、このRustPlaygroundでハッシュマップを操作できます。
演習:ハッシュマップを使用して注文を追跡する
この演習では、ハッシュマップを使用するように自動車工場のプログラムを変更します。
ハッシュマップキーと値のペアを使用して、車の注文に関する詳細を追跡し、出力を表示します。繰り返しになりますが、あなたの課題は、サンプルコードを完成させてコンパイルして実行することです。
この演習のサンプルコードで作業するには、次の2つのオプションがあります。
ノート
サンプルコードで、
todo!
マクロを探します。このマクロは、完了するか更新する必要があるコードを示します。
最初のステップは、既存のプログラムコードを取得することです。
car_quality
、car_factory
およびmain
機能を。次のコードをコピーしてローカル開発環境で編集する
か、この準備されたRustPlaygroundでコードを開きます。
#[derive(PartialEq, Debug)]
struct Car { color: String, motor: Transmission, roof: bool, age: (Age, u32) }
#[derive(PartialEq, Debug)]
enum Transmission { Manual, SemiAuto, Automatic }
#[derive(PartialEq, Debug)]
enum Age { New, Used }
// Get the car quality by testing the value of the input argument
// - miles (u32)
// Return tuple with car age ("New" or "Used") and mileage
fn car_quality (miles: u32) -> (Age, u32) {
// Check if car has accumulated miles
// Return tuple early for Used car
if miles > 0 {
return (Age::Used, miles);
}
// Return tuple for New car, no need for "return" keyword or semicolon
(Age::New, miles)
}
// Build "Car" using input arguments
fn car_factory(order: i32, miles: u32) -> Car {
let colors = ["Blue", "Green", "Red", "Silver"];
// Prevent panic: Check color index for colors array, reset as needed
// Valid color = 1, 2, 3, or 4
// If color > 4, reduce color to valid index
let mut color = order as usize;
if color > 4 {
// color = 5 --> index 1, 6 --> 2, 7 --> 3, 8 --> 4
color = color - 4;
}
// Add variety to orders for motor type and roof type
let mut motor = Transmission::Manual;
let mut roof = true;
if order % 3 == 0 { // 3, 6, 9
motor = Transmission::Automatic;
} else if order % 2 == 0 { // 2, 4, 8, 10
motor = Transmission::SemiAuto;
roof = false;
} // 1, 5, 7, 11
// Return requested "Car"
Car {
color: String::from(colors[(color-1) as usize]),
motor: motor,
roof: roof,
age: car_quality(miles)
}
}
fn main() {
// Initialize counter variable
let mut order = 1;
// Declare a car as mutable "Car" struct
let mut car: Car;
// Order 6 cars, increment "order" for each request
// Car order #1: Used, Hard top
car = car_factory(order, 1000);
println!("{}: {:?}, Hard top = {}, {:?}, {}, {} miles", order, car.age.0, car.roof, car.motor, car.color, car.age.1);
// Car order #2: Used, Convertible
order = order + 1;
car = car_factory(order, 2000);
println!("{}: {:?}, Hard top = {}, {:?}, {}, {} miles", order, car.age.0, car.roof, car.motor, car.color, car.age.1);
// Car order #3: New, Hard top
order = order + 1;
car = car_factory(order, 0);
println!("{}: {:?}, Hard top = {}, {:?}, {}, {} miles", order, car.age.0, car.roof, car.motor, car.color, car.age.1);
// Car order #4: New, Convertible
order = order + 1;
car = car_factory(order, 0);
println!("{}: {:?}, Hard top = {}, {:?}, {}, {} miles", order, car.age.0, car.roof, car.motor, car.color, car.age.1);
// Car order #5: Used, Hard top
order = order + 1;
car = car_factory(order, 3000);
println!("{}: {:?}, Hard top = {}, {:?}, {}, {} miles", order, car.age.0, car.roof, car.motor, car.color, car.age.1);
// Car order #6: Used, Hard top
order = order + 1;
car = car_factory(order, 4000);
println!("{}: {:?}, Hard top = {}, {:?}, {}, {} miles", order, car.age.0, car.roof, car.motor, car.color, car.age.1);
}
2. プログラムをビルドします。次のセクションに進む前に、コードがコンパイルされて実行されることを確認してください。
次の出力が表示されます。
1: Used, Hard top = true, Manual, Blue, 1000 miles
2: Used, Hard top = false, SemiAuto, Green, 2000 miles
3: New, Hard top = true, Automatic, Red, 0 miles
4: New, Hard top = false, SemiAuto, Silver, 0 miles
5: Used, Hard top = true, Manual, Blue, 3000 miles
6: Used, Hard top = true, Automatic, Green, 4000 miles
現在のプログラムは、各車の注文を処理し、各注文が完了した後に要約を印刷します。car_factory
関数を呼び出すたびにCar
、注文の詳細を含む構造体が返され、注文が実行されます。結果はcar
変数に格納されます。
お気づきかもしれませんが、このプログラムにはいくつかの重要な機能がありません。すべての注文を追跡しているわけではありません。car
変数は、現在の注文の詳細のみを保持しています。関数car
の結果で変数が更新されるたびcar_factory
に、前の順序の詳細が上書きされます。
ファイリングシステムのようにすべての注文を追跡するために、プログラムを更新する必要があります。この目的のために、<K、V>ペアでハッシュマップを定義します。ハッシュマップキーは、車の注文番号に対応します。ハッシュマップ値は、Car
構造体で定義されているそれぞれの注文の詳細になります。
main
関数の先頭、最初の中括弧の直後に次のコードを追加します{
。// Initialize a hash map for the car orders
// - Key: Car order number, i32
// - Value: Car order details, Car struct
use std::collections::HashMap;
let mut orders: HashMap<i32, Car> = HashMap;
2. orders
ハッシュマップを作成するステートメントの構文の問題を修正します。
ヒント
ハッシュマップを最初から作成しているので、おそらくこの
new()
メソッドを使用することをお勧めします。
3. プログラムをビルドします。次のセクションに進む前に、コードがコンパイルされていることを確認してください。コンパイラからの警告メッセージは無視してかまいません。
次のステップは、履行された各自動車注文をハッシュマップに追加することです。
このmain
関数では、car_factory
車の注文ごとに関数を呼び出します。注文が履行された後、println!
マクロを呼び出して、car
変数に格納されている注文の詳細を表示します。
// Car order #1: Used, Hard top
car = car_factory(order, 1000);
println!("{}: {}, Hard top = {}, {:?}, {}, {} miles", order, car.age.0, car.roof, car.motor, car.color, car.age.1);
...
// Car order #6: Used, Hard top
order = order + 1;
car = car_factory(order, 4000);
println!("{}: {}, Hard top = {}, {:?}, {}, {} miles", order, car.age.0, car.roof, car.motor, car.color, car.age.1);
新しいハッシュマップで機能するように、これらのコードステートメントを修正します。
car_factory
関数の呼び出しは保持します。返された各Car
構造体は、ハッシュマップの<K、V>ペアの一部として格納されます。println!
マクロの呼び出しを更新して、ハッシュマップに保存されている注文の詳細を表示します。main
関数で、関数の呼び出しcar_factory
とそれに伴うprintln!
マクロの呼び出しを見つけます。// Car order #1: Used, Hard top
car = car_factory(order, 1000);
println!("{}: {}, Hard top = {}, {:?}, {}, {} miles", order, car.age.0, car.roof, car.motor, car.color, car.age.1);
...
// Car order #6: Used, Hard top
order = order + 1;
car = car_factory(order, 4000);
println!("{}: {}, Hard top = {}, {:?}, {}, {} miles", order, car.age.0, car.roof, car.motor, car.color, car.age.1);
2. すべての自動車注文のステートメントの完全なセットを次の改訂されたコードに置き換えます。
// Car order #1: Used, Hard top
car = car_factory(order, 1000);
orders(order, car);
println!("Car order {}: {:?}", order, orders.get(&order));
// Car order #2: Used, Convertible
order = order + 1;
car = car_factory(order, 2000);
orders(order, car);
println!("Car order {}: {:?}", order, orders.get(&order));
// Car order #3: New, Hard top
order = order + 1;
car = car_factory(order, 0);
orders(order, car);
println!("Car order {}: {:?}", order, orders.get(&order));
// Car order #4: New, Convertible
order = order + 1;
car = car_factory(order, 0);
orders(order, car);
println!("Car order {}: {:?}", order, orders.get(&order));
// Car order #5: Used, Hard top
order = order + 1;
car = car_factory(order, 3000);
orders(order, car);
println!("Car order {}: {:?}", order, orders.get(&order));
// Car order #6: Used, Hard top
order = order + 1;
car = car_factory(order, 4000);
orders(order, car);
println!("Car order {}: {:?}", order, orders.get(&order));
3. 今すぐプログラムをビルドしようとすると、コンパイルエラーが表示されます。<K、V>ペアをorders
ハッシュマップに追加するステートメントに構文上の問題があります。問題がありますか?先に進んで、ハッシュマップに順序を追加する各ステートメントの問題を修正してください。
ヒント
orders
ハッシュマップに直接値を割り当てることはできません。挿入を行うにはメソッドを使用する必要があります。
プログラムが正常にビルドされると、次の出力が表示されます。
Car order 1: Some(Car { color: "Blue", motor: Manual, roof: true, age: ("Used", 1000) })
Car order 2: Some(Car { color: "Green", motor: SemiAuto, roof: false, age: ("Used", 2000) })
Car order 3: Some(Car { color: "Red", motor: Automatic, roof: true, age: ("New", 0) })
Car order 4: Some(Car { color: "Silver", motor: SemiAuto, roof: false, age: ("New", 0) })
Car order 5: Some(Car { color: "Blue", motor: Manual, roof: true, age: ("Used", 3000) })
Car order 6: Some(Car { color: "Green", motor: Automatic, roof: true, age: ("Used", 4000) })
改訂されたコードの出力が異なることに注意してください。println!
マクロディスプレイの内容Car
各値を示すことによって、構造体と対応するフィールド名。
次の演習では、ループ式を使用してコードの冗長性を減らします。
for、while、およびloop式を使用します
多くの場合、プログラムには、その場で繰り返す必要のあるコードのブロックがあります。ループ式を使用して、繰り返しの実行方法をプログラムに指示できます。電話帳のすべてのエントリを印刷するには、ループ式を使用して、最初のエントリから最後のエントリまで印刷する方法をプログラムに指示できます。
Rustは、プログラムにコードのブロックを繰り返させるための3つのループ式を提供します。
loop
:手動停止が発生しない限り、繰り返します。while
:条件が真のままで繰り返します。for
:コレクション内のすべての値に対して繰り返します。この単元では、これらの各ループ式を見ていきます。
loop
式は、無限ループを作成します。このキーワードを使用すると、式の本文でアクションを継続的に繰り返すことができます。ループを停止させるための直接アクションを実行するまで、アクションが繰り返されます。
次の例では、「We loopforever!」というテキストを出力します。そしてそれはそれ自体で止まりません。println!
アクションは繰り返し続けます。
loop {
println!("We loop forever!");
}
loop
式を使用する場合、ループを停止する唯一の方法は、プログラマーとして直接介入する場合です。特定のコードを追加してループを停止したり、Ctrl + Cなどのキーボード命令を入力してプログラムの実行を停止したりできます。
loop
式を停止する最も一般的な方法は、break
キーワードを使用してブレークポイントを設定することです。
loop {
// Keep printing, printing, printing...
println!("We loop forever!");
// On the other hand, maybe we should stop!
break;
}
プログラムがbreak
キーワードを検出すると、loop
式の本体でアクションの実行を停止し、次のコードステートメントに進みます。
break
キーワードは、特別な機能を明らかにするloop
表現を。break
キーワードを使用すると、式本体でのアクションの繰り返しを停止することも、ブレークポイントで値を返すこともできます。
次の例はbreak
、loop
式でキーワードを使用して値も返す方法を示しています。
let mut counter = 1;
// stop_loop is set when loop stops
let stop_loop = loop {
counter *= 2;
if counter > 100 {
// Stop loop, return counter value
break counter;
}
};
// Loop should break when counter = 128
println!("Break the loop at counter = {}.", stop_loop);
出力は次のとおりです。
Break the loop at counter = 128.
私たちのloop
表現の本体は、これらの連続したアクションを実行します。
stop_loop
変数を宣言します。loop
式の結果にバインドするようにプログラムに指示します。loop
式の本体でアクションを実行します:counter
値を現在の値の2倍にインクリメントします。counter
値を確認してください。counter
値が100以上です。ループから抜け出し、
counter
値を返します。
4. もしcounter
値が100以上ではありません。
ループ本体でアクションを繰り返します。
5. stop_loop
値を式のcounter
結果である値に設定しますloop
。
loop
式本体は、複数のブレークポイントを持つことができます。式に複数のブレークポイントがある場合、すべてのブレークポイントは同じタイプの値を返す必要があります。すべての値は、整数型、文字列型、ブール型などである必要があります。ブレークポイントが明示的に値を返さない場合、プログラムは式の結果を空のタプルとして解釈します()
。
while
ループは、条件式を使用しています。条件式が真である限り、ループが繰り返されます。このキーワードを使用すると、条件式がfalseになるまで、式本体のアクションを実行できます。
while
ループは、ブール条件式を評価することから始まります。条件式がと評価されるtrue
と、本体のアクションが実行されます。アクションが完了すると、制御は条件式に戻ります。条件式がと評価されるfalse
と、while
式は停止します。
次の例では、「しばらくループします...」というテキストを出力します。ループを繰り返すたびに、「カウントが5未満である」という条件がテストされます。条件が真のままである間、式本体のアクションが実行されます。条件が真でなくなった後、while
ループは停止し、プログラムは次のコードステートメントに進みます。
while counter < 5 {
println!("We loop a while...");
counter = counter + 1;
}
for
ループは、項目のコレクションを処理するためにイテレータを使用しています。ループは、コレクション内の各アイテムの式本体のアクションを繰り返します。このタイプのループの繰り返しは、反復と呼ばれます。すべての反復が完了すると、ループは停止します。
Rustでは、配列、ベクトル、ハッシュマップなど、任意のコレクションタイプを反復処理できます。Rustはイテレータを使用して、コレクション内の各アイテムを最初から最後まで移動します。
for
ループはイテレータとして一時変数を使用しています。変数はループ式の開始時に暗黙的に宣言され、現在の値は反復ごとに設定されます。
次のコードでは、コレクションはbig_birds
配列であり、イテレーターの名前はbird
です。
let big_birds = ["ostrich", "peacock", "stork"];
for bird in big_birds
iter()
メソッドを使用して、コレクション内のアイテムにアクセスします。for
式は結果にイテレータの現在の値をバインドするiter()
方法。式本体では、イテレータ値を操作できます。
let big_birds = ["ostrich", "peacock", "stork"];
for bird in big_birds.iter() {
println!("The {} is a big bird.", bird);
}
出力は次のとおりです。
The ostrich is a big bird.
The peacock is a big bird.
The stork is a big bird.
イテレータを作成するもう1つの簡単な方法は、範囲表記を使用することですa..b
。イテレータはa
値から始まりb
、1ステップずつ続きますが、値を使用しませんb
。
for number in 0..5 {
println!("{}", number * 2);
}
このコードは、0、1、2、3、および4の数値をnumber
繰り返し処理します。ループの繰り返しごとに、値を変数にバインドします。
出力は次のとおりです。
0
2
4
6
8
このコードを実行して、このRustPlaygroundでループを探索できます。
演習:ループを使用してデータを反復処理する
この演習では、自動車工場のプログラムを変更して、ループを使用して自動車の注文を反復処理します。
main
関数を更新して、注文の完全なセットを処理するためのループ式を追加します。ループ構造は、コードの冗長性を減らすのに役立ちます。コードを簡素化することで、注文量を簡単に増やすことができます。
このcar_factory
関数では、範囲外の値での実行時のパニックを回避するために、別のループを追加します。
課題は、サンプルコードを完成させて、コンパイルして実行することです。
この演習のサンプルコードで作業するには、次の2つのオプションがあります。
ノート
サンプルコードで、
todo!
マクロを探します。このマクロは、完了するか更新する必要があるコードを示します。
前回の演習でプログラムコードを閉じた場合は、この準備されたRustPlaygroundでコードを再度開くことができます。
必ずプログラムを再構築し、コンパイラエラーなしで実行されることを確認してください。
より多くの注文をサポートするには、プログラムを更新する必要があります。現在のコード構造では、冗長ステートメントを使用して6つの注文をサポートしています。冗長性は扱いにくく、維持するのが困難です。
ループ式を使用してアクションを繰り返し、各注文を作成することで、構造を単純化できます。簡略化されたコードを使用すると、多数の注文をすばやく作成できます。
main
機能、削除次の文を。このコードブロックは、order
変数を定義および設定し、自動車の注文のcar_factory
関数とprintln!
マクロを呼び出し、各注文をorders
ハッシュマップに挿入します。// Order 6 cars
// - Increment "order" after each request
// - Add each order <K, V> pair to "orders" hash map
// - Call println! to show order details from the hash map
// Initialize order variable
let mut order = 1;
// Car order #1: Used, Hard top
car = car_factory(order, 1000);
orders.insert(order, car);
println!("Car order {}: {:?}", order, orders.get(&order));
...
// Car order #6: Used, Hard top
order = order + 1;
car = car_factory(order, 4000);
orders.insert(order, car);
println!("Car order {}: {:?}", order, orders.get(&order));
2. 削除されたステートメントを次のコードブロックに置き換えます。
// Start with zero miles
let mut miles = 0;
todo!("Add a loop expression to fulfill orders for 6 cars, initialize `order` variable to 1") {
// Call car_factory to fulfill order
// Add order <K, V> pair to "orders" hash map
// Call println! to show order details from the hash map
car = car_factory(order, miles);
orders.insert(order, car);
println!("Car order {}: {:?}", order, orders.get(&order));
// Reset miles for order variety
if miles == 2100 {
miles = 0;
} else {
miles = miles + 700;
}
}
3. アクションを繰り返すループ式を追加して、6台の車の注文を作成します。order
1に初期化された変数が必要です。
4. プログラムをビルドします。コードがエラーなしでコンパイルされることを確認してください。
次の例のような出力が表示されます。
Car order 1: Some(Car { color: "Blue", motor: Manual, roof: true, age: ("New", 0) })
Car order 2: Some(Car { color: "Green", motor: SemiAuto, roof: false, age: ("Used", 700) })
Car order 3: Some(Car { color: "Red", motor: Automatic, roof: true, age: ("Used", 1400) })
Car order 4: Some(Car { color: "Silver", motor: SemiAuto, roof: false, age: ("Used", 2100) })
Car order 5: Some(Car { color: "Blue", motor: Manual, roof: true, age: ("New", 0) })
Car order 6: Some(Car { color: "Green", motor: Automatic, roof: true, age: ("Used", 700) })
プログラムは現在、ループを使用して6台の車の注文を処理しています。6台以上注文するとどうなりますか?
main
関数のループ式を更新して、11台の車を注文します。 todo!("Update the loop expression to create 11 cars");
2. プログラムを再構築します。実行時に、プログラムはパニックになります!
Compiling playground v0.0.1 (/playground)
Finished dev [unoptimized + debuginfo] target(s) in 1.26s
Running `target/debug/playground`
thread 'main' panicked at 'index out of bounds: the len is 4 but the index is 4', src/main.rs:34:29
この問題を解決する方法を見てみましょう。
このcar_factory
関数では、if / else式を使用color
して、colors
配列のインデックスの値を確認します。
// Prevent panic: Check color index for colors array, reset as needed
// Valid color = 1, 2, 3, or 4
// If color > 4, reduce color to valid index
let mut color = order as usize;
if color > 4 {
// color = 5 --> index 1, 6 --> 2, 7 --> 3, 8 --> 4
color = color - 4;
}
colors
配列には4つの要素を持ち、かつ有効なcolor
場合は、インデックスの範囲は0〜3の条件式をチェックしているcolor
私たちはをチェックしません(インデックスが4よりも大きい場合color
、その後の関数で4に等しいインデックスへのときに我々のインデックスを車の色を割り当てる配列では、インデックス値から1を減算しますcolor - 1
。color
値4はcolors[3]
、配列と同様に処理されます。)
現在のif / else式は、8台以下の車を注文するときの実行時のパニックを防ぐためにうまく機能します。しかし、11台の車を注文すると、プログラムは9番目の注文でパニックになります。より堅牢になるように式を調整する必要があります。この改善を行うために、別のループ式を使用します。
car_factory
機能、ループ式であれば/他の条件文を交換してください。color
インデックス値が4より大きい場合に実行時のパニックを防ぐために、次の擬似コードステートメントを修正してください。// Prevent panic: Check color index, reset as needed
// If color = 1, 2, 3, or 4 - no change needed
// If color > 4, reduce to color to a valid index
let mut color = order as usize;
todo!("Replace `if/else` condition with a loop to prevent run-time panic for color > 4");
ヒント
この場合、if / else条件からループ式への変更は実際には非常に簡単です。
2. プログラムをビルドします。コードがエラーなしでコンパイルされることを確認してください。
次の出力が表示されます。
Car order 1: Some(Car { color: "Blue", motor: Manual, roof: true, age: ("New", 0) })
Car order 2: Some(Car { color: "Green", motor: SemiAuto, roof: false, age: ("Used", 700) })
Car order 3: Some(Car { color: "Red", motor: Automatic, roof: true, age: ("Used", 1400) })
Car order 4: Some(Car { color: "Silver", motor: SemiAuto, roof: false, age: ("Used", 2100) })
Car order 5: Some(Car { color: "Blue", motor: Manual, roof: true, age: ("New", 0) })
Car order 6: Some(Car { color: "Green", motor: Automatic, roof: true, age: ("Used", 700) })
Car order 7: Some(Car { color: "Red", motor: Manual, roof: true, age: ("Used", 1400) })
Car order 8: Some(Car { color: "Silver", motor: SemiAuto, roof: false, age: ("Used", 2100) })
Car order 9: Some(Car { color: "Blue", motor: Automatic, roof: true, age: ("New", 0) })
Car order 10: Some(Car { color: "Green", motor: SemiAuto, roof: false, age: ("Used", 700) })
Car order 11: Some(Car { color: "Red", motor: Manual, roof: true, age: ("Used", 1400) })
このモジュールでは、Rustで使用できるさまざまなループ式を調べ、ハッシュマップの操作方法を発見しました。データは、キーと値のペアとしてハッシュマップに保存されます。ハッシュマップは拡張可能です。
loop
手動でプロセスを停止するまでの式は、アクションを繰り返します。while
式をループして、条件が真である限りアクションを繰り返すことができます。このfor
式は、データ収集を反復処理するために使用されます。
この演習では、自動車プログラムを拡張して、繰り返されるアクションをループし、すべての注文を処理しました。注文を追跡するためにハッシュマップを実装しました。
このラーニングパスの次のモジュールでは、Rustコードでエラーと障害がどのように処理されるかについて詳しく説明します。
リンク: https://docs.microsoft.com/en-us/learn/modules/rust-loop-expressions/
1593056092
There are countless Python packages easily added to any project. But there are some packages you can't help but use in every Django web app because they've proven to be extremely beneficial and time-saving.
We decided to focus on those packages, the ones you'll end up installing regularly, and explain the installation and configurations needed to get them up and running.
While some Python packages offer cool functionality needed for one specific project, the packages discussed below are the bread-and-butter of the Django packages.
Django Web Framework
But we can't jump into Django packages by talking about the Django web framework.
A web framework is comprised of modules or packages that allow developers to quickly write web applications without having to handle the precise details of the protocol and other web app management.
Django is considered a full-stack web framework in which a database, application server, template engine, authentication module, and dispatcher are all neatly combined to create a high-level framework. These individual components are included upon package installation and often just need some minor configurations for them to function correctly.
macOS Terminal
(env)User-Macbook:env user$ pip install django
Windows Command Prompt
(env)C:\Users\Owner\desktop\env> pip install django
At the time of this article, the latest version of Django is 3.0.8. To install the latest version, all you need is the command pip install django
.
If you wish to install a different version, then specify the version number as demonstrated in the command pip install django==2.1.15
. Please note that there are two equal signs after the package name, not one.
Once the installation is complete, you will need to start configuring your Django web app with a project and an application. If you want to jump right into building your Django web app, check out the quick start guides to Django Installation and Django Configuration. Or if you are just getting started and need a step-by-step tutorial, see the Beginner's Guide to Django Web Apps.
But we are here to talk about Python Packages meant for Django web apps, not basic Django configurations so we'll keep moving.
We have a lot to cover.
(1) Django TinyMCE4 Lite
macOS Terminal
(env)User-Macbook:mysite user$ pip install django-tinymce4-lite
Windows Command Prompt
(env) C:\Users\Owner\Desktop\Code\env\mysite>pip install django-tinymce4-lite
Once you have finished the basic configurations of your web app, you can install a cool Python package named django-tinymce4-lite. This package is actually a smaller version of the Django application django-tinymce4 that contains a widget to render Django form fields as TinyMCE editors.
TinyMCE is a WYSIWYG ("what you see is what you get") text editor that converts HTML elements into editor instances or "plain text". This python package is highly recommended if you are looking to create a blog as you can easily edit text that is then formatted to HTML within the actual template.
env > mysite > mysite > settings.py
INSTALLED_APPS = [
...
...
'tinymce',
]
TINYMCE_DEFAULT_CONFIG = {
'height': 400,
'width': 1000,
'cleanup_on_startup': True,
'custom_undo_redo_levels': 20,
'selector': 'textarea',
'browser_spellcheck': 'True',
'theme': 'modern',
'plugins': '''
textcolor save link image media preview codesample contextmenu
table code lists fullscreen insertdatetime nonbreaking
contextmenu directionality searchreplace wordcount visualblocks
visualchars code fullscreen autolink lists charmap print hr
anchor pagebreak
''',
'toolbar1': '''
fullscreen preview bold italic underline | fontselect,
fontsizeselect | forecolor backcolor | alignleft alignright |
aligncenter alignjustify | indent outdent | bullist numlist table |
| link image media | codesample
''',
'toolbar2': '''
visualblocks visualchars |
charmap hr pagebreak nonbreaking anchor | code |
''',
'contextmenu': 'formats | link image',
'menubar': True,
'statusbar': True,
}
After installation, you will need to add tinymce
to the list of installed apps in the settings file then add the default configurations below. The default configurations define the height, weight, spellcheck, and toolbars.
env > mysite > mysite > urls.py
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include ('main.urls')),
path('tinymce/', include('tinymce.urls')), #add this
]
Then add the TinyMCE path to the project URLs.
env > mysite > main > models.py
from django.db import models
from tinymce import HTMLField
class MyModel(models.Model):
...
content = HTMLField()
Finally, you can quickly add TinyMCE to the Django model by importing HTMLField
at the top of the page then calling it in the model field. If you are unsure of how to use Django models, check out the article, How to use Django Models for more information.
(2) Pillow
macOS Terminal
(env)User-Macbook:mysite user$ pip install Pillow
Windows Command Prompt
(env) C:\Users\Owner\Desktop\Code\env\mysite>pip install Pillow
So, this package is not specific to Django but is needed for image and file uploads to work correctly in a Django project. If you are looking to have a media upload field in your Django model for let's say an article cover image, you need to install Pillow. It's a Python Imaging Library fork for uploading files correctly.
env > mysite > mysite > settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Once installed, you need to add a media folder URL and ROOT directory to your settings file.
env > mysite > mysite > urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings #add this
from django.conf.urls.static import static #add this
urlpatterns = [
path('admin/', admin.site.urls),
path('', include ('main.urls')),
]
if settings.DEBUG: #add this
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Then you need to add the necessary imports at the top of your project's URL file and specify the URL pattern to the media folder. Keep in mind that the media upload will not work in production given the if condition. You will need to reconfigure your media upload location when you are ready to deploy.
env > mysite > main > models.py
from django.db import models
class MyModel(models.Model):
...
image = models.ImageField(upload_to='images/')
Now to upload an image, go to your models file and add an ImageField
with the upload location as 'images/'
. The uploaded images will then be added to a media > images folder that will automatically be created upon the upload.
For more information about correctly creating a model, accessing the upload location in the Django admin, and rendering the model in a template, refer to How to use Django Models.
(3) Django Crispy Forms
macOS Terminal
(env)User-Macbook:mysite user$ pip install django-crispy-forms
Windows Command Prompt
(env) C:\Users\Owner\desktop\code\env\mysite>pip install django-crispy-forms
Let's talk about Django forms. Their functionality is great but their appearance isn't the best. You can choose to install django-crispy-forms in your project to quickly solve this issue.
env > mysite > mysite > settings.py
INSTALLED_APPS = [
...
'crispy_forms',
]
CRISPY_TEMPLATE_PACK = 'uni_form'
For it to function correctly, you will need to go to the settings file and add crispy_forms
to the installed apps list. Keep in mind that there is an underscore between crispy and forms.
Then you need to specify the crispy template pack. The one listed below is the default but if you are using the Bootstrap CSS framework, check out how to integrate Bootstrap with django-crispy-forms.
env > mysite > main > templates > main > contact.html
{% load crispy_forms_tags %}
<form method="post">
{% csrf_token %}
{{form|crispy}}
<button type="submit">Submit</button>
</form>
The package django-crispy-forms is added to the project in the form of a filter added within the Django template language {{form}}
. This format will not only call all of the form fields but also format each field according to the crispy form template pack specified in the settings.
Refer to the article Render Forms with Django Crispy Forms for more information regarding the form rendering process using crispy forms and the article Build a Django Contact Form with Email Backend for more general information on how to build a Django form.
(4) Django Tables
macOS Terminal
(env)User-Macbook:mysite user$ pip install django-tables2
Windows Command Prompt
(env) C:\Users\Owner\desktop\code\env\mysite>pip install django-tables2
Now let's say you want to create a dynamic table in your Django project that connects to a model. Install django-tables2, a Django-specific package for table rendering.
env > mysite > mysite > settings.py
INSTALLED_APPS = [
...
'django_tables2',
]
Add Django tables to the installed apps.
env > mysite > main > models.py
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=100, verbose_name="full name")
email = models.EmailField(max_length=200)
Then create the model you wish to use in the table.
After you have created the model, you will need to run the commands python manage.py makemigrations
and python manage.py migrate
to add the model to the database and add your model objects via the Django admin. For more instruction, see How to Use Django Models.
env > mysite > main > (New File) tables.py
import django_tables2 as tables
from .models import MyModel
class MyTable(tables.Table):
class Meta:
model = MyModel
fields = ("name", "email", )
Now, create a new file called tables.py in the application folder, main, and import tables
from django_tables2
at the top of the file. Then create a class that specifies the model and field names.
env > mysite > main > views.py (Class-based views)
...
from django_tables2 import SingleTableView
from .models import MyModel
from .tables import MyTable
class ListView(SingleTableView):
model = MyModel
table_class = MyTable
template_name = 'main/table.html'
If you are looking to use class-based views, go to the views file and add the view class specifying the model, table, and template. Again, you will need to import the necessary variables from their appropriate files at the top of the file.
env > mysite > main > urls.py (Class-based views)
from django.urls import path
from . import views
app_name = "main"
urlpatterns = [
path("table", views.ListView.as_view()),
]
Then make sure there is a tables URL in the app urls.py file. If you are looking to learn more about class-based views, check out the article Django Class-based Views.
env > mysite > main > views.py (Function-based views)
...
from django_tables2 import SingleTableView
from .models import MyModel
from .tables import MyTable
def list(request):
model = MyModel.objects.all()
table = MyTable(model)
return render(request=request, template_name="main/table.html", context={"model":model, "table":table})
Or you can choose to do function-based views in the views.py file. Either one will work, but the format is different.
env > mysite > main > urls.py (Function-based views)
from django.urls import path
from . import views
app_name = "main"
urlpatterns = [
path("table", views.list, name="list"),
]
Then add the table URL in the app urls.py file.
env > mysite > main > templates > main > (New File) table.html
{% load render_table from django_tables2 %}
<div>
{% render_table table %}
</div>
With the views and URLs configured, you can render the table in the template by loading in render_table from django_tables2
at the top of the file then calling render_table
and the context of the table passed in the view.
By default, the class-based view passes the table context as just table
, and in the function-based view, we also chose to specify the context of the table as table
.
If you want to add Bootstrap CSS to the table:
env > mysite > main > tables.py
import django_tables2 as tables
from .models import MyModel
class MyTable(tables.Table):
class Meta:
model = MyModel
template_name = "django_tables2/bootstrap4.html"
fields = ("name", "email",)
Add a template name to the tables.py file connecting to the Bootstrap template. This and other template files can be found in the Lib > site-packages > django_tables2 > templates > django_tables2 folder of your project.
env > mysite > main > templates > main > (New File) table.html
{% extends "main/header.html" %}
{% block content %}
{% load render_table from django_tables2 %}
<div class="container">
{% render_table table %}
</div>
{% endblock %}
Then you can extend to a header that loads in the Bootstrap CDNs. This is the easiest way of adding Bootstrap to all of your templates using the same piece of code.
If you are unsure of how to use the extends tag with the Bootstrap CDNs, check out the Django extends tag and block content section in the Beginner's Guide to Django Web Apps.
(5) Django Filter
macOS Terminal
(env)User-Macbook:mysite user$ pip install django-filter
Windows Command Prompt
(env) C:\Users\Owner\desktop\code\env\mysite> pip install django-filter
Now that you have a table, you probably want the ability to search for specific content within the rows and filter the table by its results. The django-filter package can easily be used on top of the django-tables2 package to accomplish this.
env > mysite > mysite > settings.py
INSTALLED_APPS = [
...
'django_filters',
]
Add Django filters to the installed apps. Note that is django_filters
not django_filter
.
env > mysite > main > (New File) filters.py
import django_filters
from .models import MyModel
class MyFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr='icontains')
class Meta:
model = MyModel
fields = {'name', 'email'}
Now, create a new file called filters.py in the application folder, main, and import django_filters. Then list the model and the model fields you wish to filter by.
You can also choose to add django_filters.CharFilter
to the class. In the example above, the filter displays any rows where the name column contains the query specified.
You can also choose to do django_filters.CharFilter(lookup_expr='iexact')
if you are looking to filter only by an exact query match.
env > mysite > main > views.py (Class-based views)
...
from django_tables2 import SingleTableMixin
from django_filters.views import FilterView
from .models import MyModel
from .tables import MyTable
from .filters import MyFilter
class ListView(SingleTableMixin, FilterView):
model = MyModel
table_class = MyTable
template_name = 'main/table.html'
filterset_class = MyFilter
Then for a class-based view, import FilterView from django_filters.views at the top of the file and change django_tables2 import from SingleTableView
to SingleTableMixin
. You will also need to import your custom filter from the filter.py file.
In the class view, ListView
will now inherit SingleTableMixin
and FilterView
and list the filterset_class
as the custom filter within it.
env > mysite > main > templates > main > table.html
{% load render_table from django_tables2 %}
<div>
<br>
<form action="" method="GET">
{{filter.form}}
<button type="submit">Filter</button>
</form>
<br>
{% render_table table %}
</div>
With class-based views, the URL will stay the same but you will need to add a form HTML element and the Django Template language calling the filter and the form within the template. You also need a submit button within the form to submit your filter queries. Nothing changes about the way the table renders.
env > mysite > main > views.py (Function-based views)
...
from django_tables2.views import SingleTableMixin
from django_filter import FilterView
from .models import MyModel
from .tables import MyTable
def list(request):
model = MyModel.objects.all()
filterset_class = MyFilter(request.GET, model)
table = MyTable(filterset_class.qs)
return render(request=request, template_name="main/table.html", context={"model":model, "table":table, "filterset_class":filterset_class})
If using function-based views, make the same imports and the class-based views, then create an instance of the MyFilter class and pass in a GET request and model as arguments. Pass in the filterset_class
as a queryset argument in the table then lists the filterset_class
as context in the return render.
env > mysite > main > templates > main > table.html
{% load render_table from django_tables2 %}
<div>
<br>
<form action="" method="GET">
{{filterset_class.form}}
<button type="submit">Filter</button>
</form>
<br>
{% render_table table %}
</div>
With function-based views, you will need to specify the filterset_class
, or the context declared, as the filter on the form. Everything else is the same format as the class-based template.
If you are looking to style the form, either scroll back up to the Django Crispy Forms section or click at the article mentioned earlier, Render Forms with Django Crispy Forms.
(6) Python Decouple
macOS Terminal
(env)User-Macbook:mysite user$ pip install python-decouple
Windows Command Prompt
(env) C:\Users\Owner\desktop\code\env\mysite> pip install python-decouple
The last and arguably most important Python package we will discuss is python-decouple. This package hides your sensitive configuration keys and information from hackers. It was created for Django but it is now considered a "generic tool" for separating configuration settings.
env > mysite > (New File) .env
SECRET_KEY =sdjioerb43buobnodhioh4i34hgip
DEBUG =True
env > mysite > mysite > settings.py
from decouple import config
SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', cast=bool)
Create a new file named .env in the project folder then import config in the settings.py file. Then transfer all of the configuration settings and variables you wish to hide to the .env file and call each variable using the python-decouple format of config('variable')
.
#programming #django #python
1645534030
Given two user input matrix. Our task is to display the addition of two matrix. In these problem we use nested List comprehensive.
matrix multiplication in python user input
Step1: input two matrix.
Step 2: nested for loops to iterate through each row and each column.
Step 3: take one resultant matrix which is initially contains all 0. Then we multiply each row elements of first matrix with each elements of second matrix, then add all multiplied value. That is the value of resultant matrix.
# Program to multiply two matrices
A=[]
n=int(input("Enter N for N x N matrix: "))
print("Enter the element ::>")
for i in range(n):
row=[] #temporary list to store the row
for j in range(n):
row.append(int(input())) #add the input to row list
A.append(row) #add the row to the list
print(A)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
#Display the 2D array
print("Display Array In Matrix Form")
for i in range(n):
for j in range(n):
print(A[i][j], end=" ")
print() #new line
B=[]
n=int(input("Enter N for N x N matrix : ")) #3 here
#use list for storing 2D array
#get the user input and store it in list (here IN : 1 to 9)
print("Enter the element ::>")
for i in range (n):
row=[] #temporary list to store the row
for j in range(n):
row.append(int(input())) #add the input to row list
B.append(row) #add the row to the list
print(B)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
#Display the 2D array
print("Display Array In Matrix Form")
for i in range(n):
for j in range(n):
print(B[i][j], end=" ")
print()
result = [[0,0,0], [0,0,0], [0,0,0]]
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
print("The Resultant Matrix Is ::>")
for r in result:
print(r)
Enter N for N x N matrix: 3
Enter the element ::>
2
1
4
2
1
2
3
4
3
[[2, 1, 4], [2, 1, 2], [3, 4, 3]]
Display Array In Matrix Form
2 1 4
2 1 2
3 4 3
Enter N for N x N matrix : 3
Enter the element ::>
1
2
3
4
5
6
7
8
9
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Display Array In Matrix Form
1 2 3
4 5 6
7 8 9
The Resultant Matrix Is ::>
[34, 41, 48]
[20, 25, 30]
[40, 50, 60]
https://www.pakainfo.com/python-program-multiplication-of-two-matrix-from-user-input/
1641616950
Dans cet article, vous découvrirez la .append()
méthode en Python. Vous verrez également en quoi .append()
diffère des autres méthodes utilisées pour ajouter des éléments aux listes.
Commençons!
Un tableau en programmation est une collection ordonnée d'éléments, et tous les éléments doivent être du même type de données.
Cependant, contrairement à d'autres langages de programmation, les tableaux ne sont pas une structure de données intégrée à Python. Au lieu des tableaux traditionnels, Python utilise des listes.
Les listes sont essentiellement des tableaux dynamiques et sont l'une des structures de données les plus courantes et les plus puissantes de Python.
Vous pouvez les considérer comme des conteneurs commandés. Ils stockent et organisent ensemble des données similaires.
Les éléments stockés dans une liste peuvent être de n'importe quel type de données.
Il peut y avoir des listes d'entiers (nombres entiers), des listes de flottants (nombres à virgule flottante), des listes de chaînes (texte) et des listes de tout autre type de données Python intégré.
Bien qu'il soit possible pour les listes de ne contenir que des éléments du même type de données, elles sont plus flexibles que les tableaux traditionnels. Cela signifie qu'il peut y avoir une variété de types de données différents dans la même liste.
Les listes ont 0 ou plusieurs éléments, ce qui signifie qu'il peut également y avoir des listes vides. À l'intérieur d'une liste, il peut également y avoir des valeurs en double.
Les valeurs sont séparées par une virgule et placées entre crochets, []
.
Pour créer une nouvelle liste, donnez d'abord un nom à la liste. Ajoutez ensuite l'opérateur d'affectation ( =
) et une paire de crochets ouvrants et fermants. A l'intérieur des parenthèses, ajoutez les valeurs que la liste doit contenir.
#create a new list of names
names = ["Jimmy", "Timmy", "Kenny", "Lenny"]
#print the list to the console
print(names)
#output
#['Jimmy', 'Timmy', 'Kenny', 'Lenny']
Les listes maintiennent un ordre pour chaque article.
Chaque élément de la collection a son propre numéro d'index, que vous pouvez utiliser pour accéder à l'élément lui-même.
Les index en Python (et tout autre langage de programmation moderne) commencent à 0 et augmentent pour chaque élément de la liste.
Par exemple, la liste créée précédemment avait 4 valeurs :
names = ["Jimmy", "Timmy", "Kenny", "Lenny"]
La première valeur de la liste, "Jimmy", a un indice de 0.
La deuxième valeur de la liste, "Timmy", a un indice de 1.
La troisième valeur de la liste, "Kenny", a un indice de 2.
La quatrième valeur de la liste, "Lenny", a un indice de 3.
Pour accéder à un élément de la liste par son numéro d'index, écrivez d'abord le nom de la liste, puis entre crochets écrivez l'entier de l'index de l'élément.
Par exemple, si vous vouliez accéder à l'élément qui a un index de 2, vous feriez :
names = ["Jimmy", "Timmy", "Kenny", "Lenny"]
print(names[2])
#output
#Kenny
En Python, lorsque les objets sont mutables , cela signifie que leurs valeurs peuvent être modifiées une fois qu'ils ont été créés.
Les listes sont des objets modifiables, vous pouvez donc les mettre à jour et les modifier après leur création.
Les listes sont également dynamiques, ce qui signifie qu'elles peuvent augmenter et diminuer tout au long de la vie d'un programme.
Des éléments peuvent être supprimés d'une liste existante et de nouveaux éléments peuvent être ajoutés à une liste existante.
Il existe des méthodes intégrées pour ajouter et supprimer des éléments des listes.
Par exemple, pour add articles, il y a les .append()
, .insert()
et les .extend()
méthodes.
Pour supprimer des éléments, il existe les méthodes .remove()
, .pop()
et .pop(index)
.
.append()
méthode ?La .append()
méthode ajoute un élément supplémentaire à la fin d'une liste déjà existante.
La syntaxe générale ressemble à ceci :
list_name.append(item)
Décomposons-le :
list_name
est le nom que vous avez donné à la liste..append()
est la méthode de liste pour ajouter un élément à la fin de list_name
.item
est l'élément individuel spécifié que vous souhaitez ajouter.Lors de l'utilisation de .append()
, la liste d'origine est modifiée. Aucune nouvelle liste n'est créée.
Si vous souhaitez ajouter un nom supplémentaire à la liste créée précédemment, procédez comme suit :
names = ["Jimmy", "Timmy", "Kenny", "Lenny"]
#add the name Dylan to the end of the list
names.append("Dylan")
print(names)
#output
#['Jimmy', 'Timmy', 'Kenny', 'Lenny', 'Dylan']
.append()
et .insert()
?La différence entre les deux méthodes est qu'elle .append()
ajoute un élément à la fin d'une liste, alors qu'elle .insert()
insère et élément à une position spécifiée dans la liste.
Comme vous l'avez vu dans la section précédente, .append()
ajoutera l'élément que vous passez comme argument à la fonction toujours à la fin de la liste.
Si vous ne souhaitez pas simplement ajouter des éléments à la fin d'une liste, vous pouvez spécifier la position à laquelle vous souhaitez les ajouter avec .insert()
.
La syntaxe générale ressemble à ceci :
list_name.insert(position,item)
Décomposons-le :
list_name
est le nom de la liste..insert()
est la méthode de liste pour insérer un élément dans une liste.position
est le premier argument de la méthode. C'est toujours un entier - en particulier c'est le numéro d'index de la position où vous voulez que le nouvel élément soit placé.item
est le deuxième argument de la méthode. Ici, vous spécifiez le nouvel élément que vous souhaitez ajouter à la liste.Par exemple, supposons que vous disposiez de la liste suivante de langages de programmation :
programming_languages = ["JavaScript", "Java", "C++"]
print(programming_languages)
#output
#['JavaScript', 'Java', 'C++']
Si vous vouliez insérer "Python" au début de la liste, en tant que nouvel élément de la liste, vous utiliseriez la .insert()
méthode et spécifieriez la position comme 0
. (Rappelez-vous que la première valeur d'une liste a toujours un indice de 0.)
programming_languages = ["JavaScript", "Java", "C++"]
programming_languages.insert(0, "Python")
print(programming_languages)
#output
#['Python', 'JavaScript', 'Java', 'C++']
Si vous aviez plutôt voulu que "JavaScript" soit le premier élément de la liste, puis ajoutez "Python" comme nouvel élément, vous spécifieriez la position comme suit1
:
programming_languages = ["JavaScript", "Java", "C++"]
programming_languages.insert(1,"Python")
print(programming_languages)
#output
#['JavaScript', 'Python', 'Java', 'C++']
La .insert()
méthode vous donne un peu plus de flexibilité par rapport à la .append()
méthode qui ajoute uniquement un nouvel élément à la fin de la liste.
.append()
et .extend()
?Que faire si vous souhaitez ajouter plusieurs éléments à une liste à la fois, au lieu de les ajouter un à la fois ?
Vous pouvez utiliser la .append()
méthode pour ajouter plusieurs éléments à la fin d'une liste.
Supposons que vous ayez une liste qui ne contient que deux langages de programmation :
programming_languages = ["JavaScript", "Java"]
print(programming_languages)
#output
#['JavaScript', 'Java']
Vous souhaitez ensuite ajouter deux autres langues, à la fin.
Dans ce cas, vous passez une liste contenant les deux nouvelles valeurs que vous souhaitez ajouter, en argument à .append()
:
programming_languages = ["JavaScript", "Java"]
#add two new items to the end of the list
programming_languages.append(["Python","C++"])
print(programming_languages)
#output
#['JavaScript', 'Java', ['Python', 'C++']]
Si vous regardez de plus près la sortie ci-dessus, ['JavaScript', 'Java', ['Python', 'C++']]
vous verrez qu'une nouvelle liste a été ajoutée à la fin de la liste déjà existante.
Donc, .append()
ajoute une liste à l'intérieur d'une liste .
Les listes sont des objets, et lorsque vous utilisez .append()
pour ajouter une autre liste dans une liste, les nouveaux éléments seront ajoutés en tant qu'objet unique (élément).
Supposons que vous ayez déjà deux listes, comme ceci :
names = ["Jimmy", "Timmy"]
more_names = ["Kenny", "Lenny"]
Et si vous vouliez combiner le contenu des deux listes en une seule, en ajoutant le contenu de more_names
to names
?
Lorsque la .append()
méthode est utilisée à cette fin, une autre liste est créée à l'intérieur de names
:
names = ["Jimmy", "Timmy"]
more_names = ["Kenny", "Lenny"]
#add contents of more_names to names
names.append(more_names)
print(names)
#output
#['Jimmy', 'Timmy', ['Kenny', 'Lenny']]
Donc, .append()
ajoute les nouveaux éléments comme une autre liste, en ajoutant l'objet à la fin.
Pour réellement concaténer (ajouter) des listes et combiner tous les éléments d'une liste à une autre , vous devez utiliser la .extend()
méthode.
La syntaxe générale ressemble à ceci :
list_name.extend(iterable/other_list_name)
Décomposons-le :
list_name
est le nom de l'une des listes..extend()
est la méthode pour ajouter tout le contenu d'une liste à une autre.iterable
peut être n'importe quel itérable tel qu'une autre liste, par exemple, another_list_name
. Dans ce cas, another_list_name
est une liste qui sera concaténée avec list_name
, et son contenu sera ajouté un par un à la fin de list_name
, en tant qu'éléments séparés.Ainsi, en reprenant l'exemple précédent, lorsque .append()
est remplacé par .extend()
, la sortie ressemblera à ceci :
names = ["Jimmy", "Timmy"]
more_names = ["Kenny", "Lenny"]
names.extend(more_names)
print(names)
#output
#['Jimmy', 'Timmy', 'Kenny', 'Lenny']
Lorsque nous avons utilisé .extend()
, la names
liste s'est allongée et sa longueur a été augmentée de 2.
La façon dont cela .extend()
fonctionne est qu'il prend une liste (ou un autre itérable) comme argument, itère sur chaque élément, puis chaque élément de l'itérable est ajouté à la liste.
Il existe une autre différence entre .append()
et .extend()
.
Lorsque vous souhaitez ajouter une chaîne, comme vu précédemment, .append()
ajoutez l'élément entier et unique à la fin de la liste :
names = ["Jimmy", "Timmy", "Kenny", "Lenny"]
#add the name Dylan to the end of the list
names.append("Dylan")
print(names)
#output
#['Jimmy', 'Timmy', 'Kenny', 'Lenny', 'Dylan']
Si vous aviez .extend()
plutôt l' habitude d'ajouter une chaîne à la fin d'une liste, chaque caractère de la chaîne serait ajouté en tant qu'élément individuel à la liste.
C'est parce que les chaînes sont un itérable et .extend()
qu'elles itèrent sur l'argument itérable qui lui est transmis.
Ainsi, l'exemple ci-dessus ressemblerait à ceci :
names = ["Jimmy", "Timmy", "Kenny", "Lenny"]
#pass a string(iterable) to .extend()
names.extend("Dylan")
print(names)
#output
#['Jimmy', 'Timmy', 'Kenny', 'Lenny', 'D', 'y', 'l', 'a', 'n']
En résumé, la .append()
méthode est utilisée pour ajouter un élément à la fin d'une liste existante, sans créer de nouvelle liste.
Lorsqu'il est utilisé pour ajouter une liste à une autre liste, il crée une liste dans une liste.
Si vous souhaitez en savoir plus sur Python, consultez la certification Python de freeCodeCamp . Vous commencerez à apprendre de manière interactive et conviviale pour les débutants. Vous construirez également cinq projets à la fin pour mettre en pratique ce que vous avez appris.
Merci d'avoir lu et bon codage!
Link: https://www.freecodecamp.org/news/append-in-python-how-to-append-to-a-list-or-an-array/
1641884883
Neste artigo, você aprenderá sobre o .append()
método em Python. Você também verá como .append()
difere de outros métodos usados para adicionar elementos a listas.
Vamos começar!
Uma matriz na programação é uma coleção ordenada de itens e todos os itens precisam ser do mesmo tipo de dados.
No entanto, ao contrário de outras linguagens de programação, os arrays não são uma estrutura de dados embutida no Python. Em vez de arrays tradicionais, o Python usa listas.
Listas são essencialmente arrays dinâmicos e são uma das estruturas de dados mais comuns e poderosas em Python.
Você pode pensar neles como contêineres ordenados. Eles armazenam e organizam tipos semelhantes de dados relacionados juntos.
Os elementos armazenados em uma lista podem ser de qualquer tipo de dados.
Pode haver listas de inteiros (números inteiros), listas de floats (números de ponto flutuante), listas de strings (texto) e listas de qualquer outro tipo de dados interno do Python.
Embora seja possível que as listas contenham apenas itens do mesmo tipo de dados, elas são mais flexíveis do que as matrizes tradicionais. Isso significa que pode haver uma variedade de tipos de dados diferentes dentro da mesma lista.
As listas têm 0 ou mais itens, o que significa que também pode haver listas vazias. Dentro de uma lista também pode haver valores duplicados.
Os valores são separados por uma vírgula e colocados entre colchetes, []
.
Para criar uma nova lista, primeiro dê um nome à lista. Em seguida, adicione o operador de atribuição ( =
) e um par de colchetes de abertura e fechamento. Dentro dos colchetes, adicione os valores que você deseja que a lista contenha.
#create a new list of names
names = ["Jimmy", "Timmy", "Kenny", "Lenny"]
#print the list to the console
print(names)
#output
#['Jimmy', 'Timmy', 'Kenny', 'Lenny']
As listas mantêm uma ordem para cada item.
Cada item na coleção tem seu próprio número de índice, que você pode usar para acessar o próprio item.
Índices em Python (e em qualquer outra linguagem de programação moderna) começam em 0 e aumentam para cada item da lista.
Por exemplo, a lista criada anteriormente tinha 4 valores:
names = ["Jimmy", "Timmy", "Kenny", "Lenny"]
O primeiro valor na lista, "Jimmy", tem um índice de 0.
O segundo valor na lista, "Timmy", tem um índice de 1.
O terceiro valor na lista, "Kenny", tem um índice de 2.
O quarto valor na lista, "Lenny", tem um índice de 3.
Para acessar um elemento na lista por seu número de índice, primeiro escreva o nome da lista, depois entre colchetes escreva o inteiro do índice do elemento.
Por exemplo, se você quisesse acessar o elemento que tem um índice de 2, você faria:
names = ["Jimmy", "Timmy", "Kenny", "Lenny"]
print(names[2])
#output
#Kenny
Em Python, quando os objetos são mutáveis , significa que seus valores podem ser alterados depois de criados.
As listas são objetos mutáveis, portanto, você pode atualizá-las e alterá-las depois de criadas.
As listas também são dinâmicas, o que significa que podem crescer e diminuir ao longo da vida de um programa.
Os itens podem ser removidos de uma lista existente e novos itens podem ser adicionados a uma lista existente.
Existem métodos internos para adicionar e remover itens de listas.
Por exemplo, para add itens, há as .append()
, .insert()
e .extend()
métodos.
Para remove itens, há as .remove()
, .pop()
e .pop(index)
métodos.
.append()
método faz?O .append()
método adiciona um elemento adicional ao final de uma lista já existente.
A sintaxe geral se parece com isso:
list_name.append(item)
Vamos decompô-lo:
list_name
é o nome que você deu à lista..append()
é o método de lista para adicionar um item ao final de list_name
.item
é o item individual especificado que você deseja adicionar.Ao usar .append()
, a lista original é modificada. Nenhuma nova lista é criada.
Se você quiser adicionar um nome extra à lista criada anteriormente, faça o seguinte:
names = ["Jimmy", "Timmy", "Kenny", "Lenny"]
#add the name Dylan to the end of the list
names.append("Dylan")
print(names)
#output
#['Jimmy', 'Timmy', 'Kenny', 'Lenny', 'Dylan']
.append()
e .insert()
?A diferença entre os dois métodos é que .append()
adiciona um item ao final de uma lista, enquanto .insert()
insere um item em uma posição especificada na lista.
Como você viu na seção anterior, .append()
irá adicionar o item que você passar como argumento para a função sempre no final da lista.
Se você não quiser apenas adicionar itens ao final de uma lista, poderá especificar a posição com a qual deseja adicioná-los .insert()
.
A sintaxe geral fica assim:
list_name.insert(position,item)
Vamos decompô-lo:
list_name
é o nome da lista..insert()
é o método de lista para inserir um item em uma lista.position
é o primeiro argumento para o método. É sempre um número inteiro - especificamente é o número de índice da posição onde você deseja que o novo item seja colocado.item
é o segundo argumento para o método. Aqui você especifica o novo item que deseja adicionar à lista.Por exemplo, digamos que você tenha a seguinte lista de linguagens de programação:
programming_languages = ["JavaScript", "Java", "C++"]
print(programming_languages)
#output
#['JavaScript', 'Java', 'C++']
Se você quisesse inserir "Python" no início da lista, como um novo item da lista, você usaria o .insert()
método e especificaria a posição como 0
. (Lembre-se de que o primeiro valor em uma lista sempre tem um índice de 0.)
programming_languages = ["JavaScript", "Java", "C++"]
programming_languages.insert(0, "Python")
print(programming_languages)
#output
#['Python', 'JavaScript', 'Java', 'C++']
Se, em vez disso, você quisesse que "JavaScript" fosse o primeiro item da lista e, em seguida, adicionasse "Python" como o novo item, você especificaria a posição como 1
:
programming_languages = ["JavaScript", "Java", "C++"]
programming_languages.insert(1,"Python")
print(programming_languages)
#output
#['JavaScript', 'Python', 'Java', 'C++']
O .insert()
método oferece um pouco mais de flexibilidade em comparação com o .append()
método que apenas adiciona um novo item ao final da lista.
.append()
e .extend()
?E se você quiser adicionar mais de um item a uma lista de uma só vez, em vez de adicioná-los um de cada vez?
Você pode usar o .append()
método para adicionar mais de um item ao final de uma lista.
Digamos que você tenha uma lista que contém apenas duas linguagens de programação:
programming_languages = ["JavaScript", "Java"]
print(programming_languages)
#output
#['JavaScript', 'Java']
Você então deseja adicionar mais dois idiomas, no final dele.
Nesse caso, você passa uma lista contendo os dois novos valores que deseja adicionar, como argumento para .append()
:
programming_languages = ["JavaScript", "Java"]
#add two new items to the end of the list
programming_languages.append(["Python","C++"])
print(programming_languages)
#output
#['JavaScript', 'Java', ['Python', 'C++']]
Se você observar mais de perto a saída acima, ['JavaScript', 'Java', ['Python', 'C++']]
, verá que uma nova lista foi adicionada ao final da lista já existente.
Então, .append()
adiciona uma lista dentro de uma lista .
Listas são objetos, e quando você usa .append()
para adicionar outra lista em uma lista, os novos itens serão adicionados como um único objeto (item).
Digamos que você já tenha duas listas, assim:
names = ["Jimmy", "Timmy"]
more_names = ["Kenny", "Lenny"]
E se você quiser combinar o conteúdo de ambas as listas em uma, adicionando o conteúdo de more_names
a names
?
Quando o .append()
método é usado para essa finalidade, outra lista é criada dentro de names
:
names = ["Jimmy", "Timmy"]
more_names = ["Kenny", "Lenny"]
#add contents of more_names to names
names.append(more_names)
print(names)
#output
#['Jimmy', 'Timmy', ['Kenny', 'Lenny']]
Então, .append()
adiciona os novos elementos como outra lista, anexando o objeto ao final.
Para realmente concatenar (adicionar) listas e combinar todos os itens de uma lista para outra , você precisa usar o .extend()
método.
A sintaxe geral fica assim:
list_name.extend(iterable/other_list_name)
Vamos decompô-lo:
list_name
é o nome de uma das listas..extend()
é o método para adicionar todo o conteúdo de uma lista a outra.iterable
pode ser qualquer iterável, como outra lista, por exemplo, another_list_name
. Nesse caso, another_list_name
é uma lista que será concatenada com list_name
, e seu conteúdo será adicionado um a um ao final de list_name
, como itens separados.Então, tomando o exemplo anterior, quando .append()
for substituído por .extend()
, a saída ficará assim:
names = ["Jimmy", "Timmy"]
more_names = ["Kenny", "Lenny"]
names.extend(more_names)
print(names)
#output
#['Jimmy', 'Timmy', 'Kenny', 'Lenny']
Quando usamos .extend()
, a names
lista foi estendida e seu comprimento aumentado em 2.
A maneira como .extend()
funciona é que ele pega uma lista (ou outro iterável) como argumento, itera sobre cada elemento e, em seguida, cada elemento no iterável é adicionado à lista.
Há outra diferença entre .append()
e .extend()
.
Quando você deseja adicionar uma string, como visto anteriormente, .append()
adiciona o item inteiro e único ao final da lista:
names = ["Jimmy", "Timmy", "Kenny", "Lenny"]
#add the name Dylan to the end of the list
names.append("Dylan")
print(names)
#output
#['Jimmy', 'Timmy', 'Kenny', 'Lenny', 'Dylan']
Se, em .extend()
vez disso, você adicionasse uma string ao final de uma lista, cada caractere na string seria adicionado como um item individual à lista.
Isso ocorre porque as strings são iteráveis e .extend()
iteram sobre o argumento iterável passado para ela.
Então, o exemplo acima ficaria assim:
names = ["Jimmy", "Timmy", "Kenny", "Lenny"]
#pass a string(iterable) to .extend()
names.extend("Dylan")
print(names)
#output
#['Jimmy', 'Timmy', 'Kenny', 'Lenny', 'D', 'y', 'l', 'a', 'n']
Resumindo, o .append()
método é usado para adicionar um item ao final de uma lista existente, sem criar uma nova lista.
Quando é usado para adicionar uma lista a outra lista, cria uma lista dentro de uma lista.
Se você quiser saber mais sobre Python, confira a Certificação Python do freeCodeCamp . Você começará a aprender de maneira interativa e amigável para iniciantes. Você também construirá cinco projetos no final para colocar em prática o que aprendeu.
fonte: https://www.freecodecamp.org