2022/06/01

CNN10 Script [2022/5/27]

 


CARL AZUZ, CNN 10 ANCHOR: 
This is it, our last show of the 2022 spring season and we`re so glad you could take minutes to watch it. 

My name is Carl Azuz, and our objective coverage of world events begins in China.
*coverage: 報道

Government media there say more than 1,000 people took part in an emergency online meeting this week. 

The focus: how to help the Chinese economy, the second largest in the world, as it struggles from the communist country`s response to the ongoing COVID pandemic.
*struggles from: 取り組む・もがく

While many other nations are learning to live with the disease, China has maintained a strict zero COVID policy and what that tries to do is crush every chain of COVID
transmission. 

That includes mandatory quarantines, quick lockdowns, closed borders, mass testing and contact tracing which follows people wherever they go.
*mandatory: 義務の
*quarantines: 検疫

But a growing side effect of this is that it`s hurting China`s economic growth.

International investment banks expect it`ll be significantly less this year than it was last year. 

At the meeting, China`s government announced dozens of new efforts to stimulate the economy, including more tax refunds, loans to small businesses and emergency loans to industries that are struggling. 

But though some of China`s COVID rules are being relaxed, the nation`s still pushing forward with the controversial zero COVID policy and that`s created immense challenges during the omicron variant of the disease because while it`s less severe than other versions of coronavirus, it`s more contagious.
*controversial: 物議を醸す
*immense: 計り知れない
*variant: 変異体
*contagious: 伝染性

CNN estimates that China`s restrictions are impacting 220 million people across the country. Here`s how:

(BEGIN VIDEOTAPE)

SELINA WANG, CNN INTERNATIONAL CORRESPONDENT: This is part of my daily routine in Beijing. 

All right, getting my temperature checked, mandatory testing for the city`s 20 million plus residents.

I`ve got to show them my passport and they have to type it in every single time.

In Beijing, nearly all public activity has been halted indefinitely, over just a few dozen daily COVID cases.
*indefinitely: 無期限に

Not a soul in sight in the center of Beijing`s luxury shopping district. 

All non-essential stores have been shut down, including schools and gyms, and all-in restaurant dining is banned indefinitely.

The only crowds in Beijing are parades of COVID workers spraying disinfectant all over the streets.
*disinfectant: 消毒剤

Officials here are cracking down early and aggressively to try and avoid the failures of the months-long lockdown in Shanghai.

So, it`s green, I`m good to go in. I need this green code to enter any area in Beijing. 

If it turns red, then I could be stuck at home or sent to quarantine. 

Through these smartphone apps authorities can carefully track the movements of virtually all of China`s 1.4 billion people. 

If a COVID case is later found at this grocery store, authorities can quickly contact trace and figure out whose code needs to turn red.

Grocery shelves here fully stocked. 

Beijing officials clearly trying to show people that no matter how long this partial lockdown lasts for people are going to be fed. 

It`s not going to be like in Shanghai where people have been struggling to get enough food and daily essentials in lockdown.

This is a building where a positive COVID case has been found. 

You can see the workers in hazmat suits the blue barrier around the building. 
*hazmat suit: 防護服

This is to keep the people who live there locked inside but it also serves as a warning to other residents. 

There`s a fear that if you spend too much time by a lockdown building, your QR code could turn red.

This is just one of the many high-risk areas in Beijing residents avoid even transiting through the red dots on the map. 

It`s lunchtime in Beijing`s most popular food district. 

Normally people here would be gathered crowded shoulder to shoulder. 

But now, it is essentially a ghost town.

With even most parks closed, there`s nowhere for people to gather and see friends except for by the side of the road to these unofficial public spaces.

And even here, there are signs reminding people to avoid crowds and security guards on the loudspeakers telling people to distance themselves.

But after more than two years of these on and off restrictions, people are getting frustrated.

A student protest even broke out at one of China`s most prestigious universities over harsh COVID policies.
*prestigious: 一流
*harsh: ひどい

Every part of our days are tracked and surveilled. 
*surveilled: 調査する

People are concerned that this control is here to stay long after COVID is gone.
Selina Wang, CNN, Beijing.

(END VIDEOTAPE)
(BEGIN VIDEO CLIP)

AZUZ (voice-over): Ten-second trivia:

Which of these American car brands is the oldest? Cadillac, Chevrolet, Ford or Lincoln? Cadillac rolled onto the scene in 1902, making it the oldest carmaker on this list.

(END VIDEO CLIP)

AZUZ: The average car in America is now a teenager. 

Let me explain, Americans are holding on to their vehicles longer than ever. 

This is according to S&P global mobility, which examines data from automotive markets. 

Now the average car on the road is just over 13 years old, which means many are much older. 

And the average light truck is about 11-1/2 years old.

So combined, the vehicles we commonly drive are over 12. 

Analysts say there are several reasons. 

For one thing, there`s an ongoing shortage of computer chips and car parts for new vehicles. 

That`s hurt their sales and driven prices up.

The used car market has been affected. 

Prices for previously owned vehicles hit an all-time high early this year, though they`ve dropped a little since then. 

Analysts say some cars are lasting longer than they used to, so people don`t need to get rid of them. 
*get rid of: 取り除く

And junkyards are reporting their lowest scrap rate in decades, so people are putting more miles on what they have.

In rocket launching news, you hear a lot about SpaceX. 

There`s another private American company. 

One of its competitors that has also received billions in funding from NASA. 

That company is Boeing. It also makes passenger planes, and its Starliner spacecraft just completed its first successful mission to the International Space Station.

It returned to Earth this week in the desert of New Mexico. 

This was an uncrewed mission. 

Boeing hopes to send up astronauts by the end of the year, but it still has challenges to overcome. 

In this flight, there were problems with some of its thrusters which helped maneuver Starliner in space.
*thrusters : スラスター
*maneuver : 操縦

(BEGIN VIDEOTAPE)

ANNOUNCER: Three, two, one -- and liftoff. 

The Starliner is headed back to space on the shoulders of Atlas, powered by a workforce dedicated to its success.
*dedicated : 打ち込んだ

SUBTITLE: Boeing finally had a successful test launch of its Starliner rocket.

UNIDENTIFIED MALE: We know now, however, who will build those spacecraft.

SUBTITLE: In 2014, NASA awarded Boeing and SpaceX contracts to develop rockets to bring astronauts to space.

Boeing has faced a myriad of problems and delays on its way to this milestone.
*myriad : 無数

A 2019 launch was forced to return to Earth because Starliner`s internal clock was off by 11 hours.

In 2021, sticking valves caused a launch to be scratched before the Starliner was sent back to the Boeing factor to be fixed.
*sticking valves : エンジンバルブ?

In the time Boeing took to have its first successful uncrewed launch, SpaceX has had six astronaut launches for NASA.

One NASA official said that because it was used to the Boeing process, it focused a little more on SpaceX and its non-traditional approach.

And another NASA official admitted not enough about Starliner was understood.

(END VIDEOTAPE)

AZUZ: Hard to think of a better story for our 10 out of 10 segment than a sharkcano. 

Yeah, a sharkcano. A NASA satellite recently photographed a plume of discolored water in the Pacific Ocean.
*plume : マグマ上昇流

Scientists say this is where an undersea volcano in the Solomon Islands is continuously erupting and an expedition here in 2015 found that the crater
is home to silky and hammerhead sharks.
*erupting : 噴火
*expedition : 探検

They`re apparently able to tolerate the hot and acidic water so it`s a sharkcano.
*tolerate : 許容する

You`d have to be pretty cal-daring to swim down there. 

Few things are crater than a shark that gives vent to its rage. 

No one would have to ask you to lava. 

You wouldn`t lack a list of reasons to quit being sill and swim from the hill like mag-mama told you to.

I`m Carl Azuz, and that takes a bite out of our last show of the season.

I want to give a shout-out to Jones Magnet Middle School and all of our viewers watching in Hampton, Virginia.

We`ve got some new stuff in the works, so please keep up with us on our YouTube channel, and this here daily show will resume in August. 

From all of us here at CNN 10, thank you for being the best audience in news.
END

2022/05/29

python グラフの書き方

何故サイトでpythonのグラフの書き方が違うのか


plt? figure? axes?
サイトで違うことが書いてあって困惑してる人多いと思います.


matplotlibには
  • オブジェクト志向
  • インタフェース志向
2種類のプロットの仕方があります.この辺が混乱を招いているような気がするのでここで整理しておきます.


オブジェクト志向でプロット


個人的にはインタフェース志向よりオブジェクト志向がオススメです.


オブジェクト志向で簡単なグラフを描いてみます
import matplotlib.pyplot as plt
import numpy as np
import math
x = np.arange(0, 10, 0.01)
y_1 = [math.cos(i) for i in x]
y_2 = [i**2 for i in x]

fig, ax = plt.subplots(1, 2)
fig.suptitle('figure')
ax[0].plot(x, y_1)
ax[0].set_title('axes[0]')
ax[1].plot(x, y_2)
ax[1].set_title('axes[1]')
plt.show()

グラフがこちら

matplolibでの構造

まず,figureと呼ばれるグラフを描写するための枠組みがあります.
figure

その中にaxesと呼ばれるグラフオブジェクトが入っています.
axes

因みに,axesの下に軸に関するデータをまとめるaxisというオブジェクトが入っています.

インタフェース志向でプロット

今度はインタフェース志向で簡単なグラフを描いてみます.
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
import numpy as np
import math
x = np.arange(0, 10, 0.01)
y = [math.cos(i) for i in x]

plt.plot(x, y)
plt.show()

グラフがこちら

pltから直接グラフを描く方法です.明示的に書かなくてもオブジェクトを自動的に生成してくれます.



2022/05/28

ブログの理想的なレイアウトを考える

理想のサイトデザイン



ブログの投稿記事数が10を超えましたが,悩んでることが....


めっちゃ見ずらい!


デザインを勉強したことはないですが,自分なりに色々調べて理想のレイアウトを追い求めていきたいと思います.

ちなみに当サイトはgoolge提供のbloggerというサービスを使っています.正直使い勝手良くないので,WordPressとかの方が良かったかも


デザインを変更するには



という訳で,最初に選択したテンプレートはこちら.


ちょっと見ずらいというか,退屈なレイアウト.
今回はこれを何とかしてみます.


カスタマイズするには,左のタブからテーマを選択し
テーマ選択画面


カスタマイズ をクリックするとカスタマイズ用のページに移行します. 
カスタマイズ画面


ここで,左の詳細設定のタブの中に,"CSSを追加"という項目があります.ここから,CSS記法を使って細かいデザインを行うことが出来ます.覚えておきましょう.


基本的なレイアウト


ページの記事の幅

記事部分の表示幅狭いなーと思ったので,調べてみると色んな有名サイトは500px ~ 750pxで収まっているみたいです(参考元サイト).意外.広すぎると目が疲れるので読んでくれなくなるそうです.

googleのサービスであるbloggerではデフォルトが860px.このままちょっと大きいですが変更せずにいきます.


文字サイズ

次に変更するのは文字サイズ.これも調べてみると13~18pxが多いですが,googleは16pxが推奨だそう.16pxに変更します.


行間の余白は1.5em.つまり1.5文字分の間隔が最適.だそうです.
行間は "CSSを追加" の欄に以下の通りに書き加えることで,変更できます.



カラーデザイン

サイトのデザインにおいて,

  • ベース (70%)
  • メイン (25%)
  • アクセント (5%)

の3色を予め決めておくと,統一感のあるデザインに仕上がります.


ベース

サイトの背景色で,全体の70%を占めます.白・黒・グレーなど,邪魔しない色を選択しましょう.


メイン

サイトのテーマカラーです.見出しやヘッダーに使用します.今回は#00ADB5を選択しました.


アクセント

ワンポイント入れる時の色です.明るい目立つ色,メインの対照色を選択しましょう.今回は#F9AA33を選択しました.


見出しのカスタマイズ




この単調すぎる見出しのデザインを何とかしていきます.


大見出し・見出しは文章の要点をまとめたもので,文章のブロックが区切られます.なので目立つようなデザインに変更します.

小見出し・準見出しでは記事を構造化し,読みやすくさせる役割が大きいです.シンプルなデザインにすることで,文章の流れを邪魔しないことを意識しましょう.


"CSSを追加"の欄に

.post-body h2{ 
  marigin: 0.25rem 0.5rem;
  padding: 1rem 2rem;
  color: #ffffff;
  background: #00ADB5;
  -webkit-box-shadow: 5px 5px 0 #007B7F;
  box-shadow: 5px 5px 0 #007B7F;
  font-size: 1.5rem;
}

.post-body h3{
  padding: 0.25rem 0.5rem;
  margin: 0.5rem 0;
  border-bottom: 5px solid #00ADB5;
  font-size: 1.2rem;
}

.post-body h4{
  padding: 0.25rem 0.5rem;
  margin: 0.5rem 0;
  border-left: 5px solid #00ADB5;
  font-size: 1.2rem;
}

を書き加えます.


完成したのがこちら


見出しである<h2>はサイドバーのタイトル部分にも使用されているので,変更が上手く反映されません.HTMLの編集画面から直接変更を加えれば何とかなりそうですが,素人は怖いので止めておきます.


<h1>は通常ブログタイトルとかでメインに使用されるらしいので使用は控える方向でやっていきます.


文装飾のデザイン


アンダーライン

一部分を強調したい時に使いたいのがアンダーラインです.
ただ,デフォルトだと地味でイマイチ.


"CSSを追加"の欄に

.post-body u{
  background: linear-gradient(transparent 50%, #89E3FF 50%);
  text-decoration: none;
}

完成形がこちら.目立つようになりましたね


箇条書き

次は箇条書きです.デフォルトがコレ.

普通です.


"CSSを追加"の欄に

.post-body ul{
  border: 3px solid #000000;
  padding: 2rem 2rem;
}

これで
こう変わります.分かりやすくなったでしょう.多分.


文章のルールを決める



文章を書く時のルールを決めて,記事を構造化し読みやすくします.やっていない人が多いけど意外と大事.


見出しのルール


見出し<h2>

見出し<h2>の役割はその章の要約です.

  • "何について話しているか" を書く.
  • 1センテンスに収める.
  • 見出し以下の文章が1ブロックとして完結していて,記事の途中から読み進めても理解できるようにする.
  • 他の見出しと情報の粒度を揃える.


見出し<h3><h4>

見出し<h3><h4>の役割は文章の構造化です.

  • "その章の結論は何か" を書く.
  • <h2>でのトピックを細分化し,整理する.
  • <h3>以下で書く結論は1つに絞る

文章装飾のルール

太字部分と下線部分だけでその記事の大枠を掴めるような構造を意識しましょう.


太字

キーワード主語が太字になります.

下線

結論部分目的語が下線になります.

2022/05/27

galaxy wathc 4 購入後半年レビュー!良い点・悪い点

 galaxy watch 4 を使い始めて半年経ちました.レビュー等,書いていこうと思います.


ラインナップ


galaxy watch 4 ですが,実は色んなラインナップが準備されています.ここでざっくり解説していきます.


無印 と Classic

無印 と Classic と2種類のデザイン・サイズが違うモデルが用意されています.
バッテリー容量が違うくらいで中身はほとんど一緒です

無印版

サイズは40mm, 44mmの2種類
色はグリーン・ピンクゴールド・シルバーの3色展開
価格は40mmが約28,000円44mmが約30,000円 (2022年5月現在)
グリーン

ピンクゴールド

シルバー


Classic 版


サイズは42mm, 46mmの2種類
色はブラック・シルバーの2色展開
回転ベゼルがついていて,スクロール操作などに使用できます.
価格は42mmが約36,000円46mmが約43,000円 (2022年5月現在)
ブラック
シルバー



通常版とLTE版

通常版ではスマホとbuletooth接続され,通信しています.
LTE版であれば電波局との通信機能が追加され,スマホが傍になくても通信が可能になります


どのモデルを買えばいいの?

買ってみての個人的な意見を書いてみます.ちなみに僕は無印版の44mm・グリーンを購入しました.

スペックについて

正直,どのモデルでも大きな性能差はないです
Classic版の回転ベゼルですが,無印版を使う限り機能としては必須って感じでもないです.なので,Classic版と通常版だとデザイン以外はほとんど一緒って考えても良いと思います.


バッテリーは1日1時間充電すれば問題なし.って感じです.食事や風呂の時間とかで十分足ります.


サイズについて

ですが,僕(一般成人男性)で44mmだと本体サイズは丁度良くて,ベルトが少し長いって感じです.問題なく使えていますね.だた,女性や小柄な方は小さいサイズを選んだほうが良いと思います.


デザインについて

実物は写真よりも落ち着いたトーンになっています.グリーンは派手過ぎる,っていう心配は不要.色が原因で服とのコーディネートが難しくなるってことはないと思います.


LTEモデル or 通常版

スマホを手放して出かけるっていうシチュエーションを想像しにくいので,個人的には通常版で良いのかなって意見です.スマートウォッチだけでスマホの代役は果たせないのでやっぱりスマホは必要になるかも.


何ができるの??

google paly store が使えるので,アプリがあればなんでも出来ます.ただ,使わない機能なんかもあるので,個人的な意見を交えつつ解説します.


使える大まかな機能
  • 健康管理
  • 通知
  • 音楽
  • ライン
  • 地図案内


健康管理

心拍数やら,歩数やらを計測してくれます.登山とかするので,そういった場面では役立つかな???運動する方にはありがたい機能.個人的にはあったら嬉しいけどなくても別にいいや


通知

スマホの通知が見れます.ただこれだけの機能ですけど,めっっっちゃ便利わざわざスマホを取り出して確認しなくても良いのはすごい楽.

下らないメールの通知の為に気を使わなくていいのは最高.手元でサッと確認して重要なメールだったらスマホから返信,みたいな使い方がベスト


音楽

これも同様.スマホを取り出さなくても,好きな音楽に切り替えたりできます.Spotifyにも対応.本体に音楽を保存ができ,buletoothイヤホンも接続できるので,buletoothイヤホンとgalaxy watch 4だけで音楽聞きながらランニングなんかも出来ます.



ライン

最近念願アプリがリリースされ,galaxy watch 4で使えるように.正直,文字入力機能は微妙なので長文の返事は現実的ではないです.ただ,決められた返事をテンプレートとして保存できるので,"了解","ありがとう",みたいな簡単な返事はワンタップで一瞬でできます.


地図案内

文字通り.案内してくれます.スマホを見ながら歩き回る必要はありません.ちゃんと地図まで表示してくれるので安心.ただ,電車の乗換案内はできません.なんで???????スマホ側から調べる必要があります.この辺はgoogleがいつか修正してくれるでしょう.歩と,カーナビはちゃんと対応してます僕はバイク乗る時とかに重宝してます.


モバイル決済

使えません.えーーーーー.一応samsung payって機能があるんですが,日本未対応です.この辺も将来に期待.頼むぞ.


Google Assistant

これも使えません."OK, google"ってやつですね.これ便利なんですけど,あんま使っている人見ませんね....僕はヘビーユーザーなんで,galaxy watch 4を買ってから使えないことを知り,一番ショックでした.まぁ,皆さんはどうでもいいと思いますけど.でも,これは2022年夏頃に実装されるみたいな噂が出てるので 期待 大 です.


スマートウォッチ購入のススメ

購入前に気をつけたい点

スマートウォッチを実際に使ってみて感じた,購入時に外せない項目をリストアップしてみます.

  • wear OS 搭載
  • 解像度が高い (dpiが高い)
  • バッテリー持続時間
  • 本体重量・ベルトの質感
  • NFC機能


wear OS搭載

スマートウォッチの一番の利点はわざわざ取り出さなくてもクイックにアクセスできる点です.

スマホの機能拡張が一番の売りだと思うので,個人的にwear OS搭載は必須です.


解像度が高い

スマートウォッチはアクセサリーとしての一面も持っているので,画面の解像度が低いとちょっと安っぽく見えてしまいます.最近のスマートウォッチは軒並み解像度が高いので,人気製品であれば心配無用な気がしますが.


バッテリー持続時間

欲を言うと2日間は充電無しで駆動して欲しいですね.正直galaxy watch 4 は他の製品と比べてこのバッテリー持続時間が良くないです.体感1日半くらいで充電切れます.ただ,他のレビューサイトがいうほど気にはならないかな.不満とまではいかないけど,満足もしていない点です.


本体重量・ベルトの質感

身につけるモノなので,気にしたいポイントですね.こればっかりは実物を見て確認するしかないです.特にラバーのベルトは品質が問われます.まぁ,ベルトは交換すればいいだけなんですけど.

galaxy watch 4 のベルトは良いですよ!蒸れない,ベタつかない.


NFC機能

主には改札で交通系ICとして使用したり,タッチ決済したりする機能です.galxy watch 4はこれらの機能がほとんど使えません一番の不満点.アプリ自体や機能は存在するみたいですが日本未対応です.対応にむけて修正作業が進めば使えるようになるかも?


正直いらなかった機能

買ってからあんまり使わなかった点・不満点もリストアップしておきます.

  • 健康管理機能全般
  • オリジナルアプリ類

健康管理機能全般

血圧とか,体組織を計測したりできますが,正直使わない.睡眠管理機能は良いですけどね.早く寝る習慣がつきました.


オリジナルアプリ

プリセットでインストールされているアプリがあります.でも,スマホと連携する特性上google謹製アプリの方が使い勝手は良いです.使わないから邪魔ってだけで別に害はない.


まとめ

ガジェットとして25,000円は正直高いですが,凄い便利な腕時計と考えれば買う価値はあるのかな,と思います.
どのスマートウォッチを買えばいいか迷ってる人は,
  • ビジネスシーンなどで使いたい → galaxy watch 4
  • スポーツの時に使いたい → 他の製品
と思ってください.


買ってよかったと思える商品だったので,スマートウォッチに興味がある.どれを買えばいいか悩んでいる方は是非買ってみて下さい.


2022/05/24

Pyhton list ポータル

初期化


URL 

基本的な初期化一般的な初期化

要素を指定して初期化
要素数を指定して初期化
多次元リストを初期化
要素を指定して多次元リストを初期化
要素数を指定して多次元リストを初期化

数列

自然数のみの数列
奇数のみの数列
等差数列
等比数列

応用

素数のみからなるリスト
条件で値が変更される数列
行列


アクセス


URL 

インデックス

i 番目の要素にアクセスする
後ろから i 番目の要素にアクセスする

スライス

スライスを使用して,好きな範囲・順番で取り出す
先頭から i 番目までの要素を取り出す
末尾から i 番目までの要素を取り出す
逆順で要素を取り出す

for文を使ってデータにアクセスする一個づつ参照する

リストの要素へ逆順にアクセス
リストの要素とインデックスを同時に取得
複数のリストを同時に取得

内容物の検索

要素Xが存在しているか調べる
要素Xの個数を調べる
要素Xの位置を調べる


末尾にデータを追加する
指定した場所にデータを追加する

削除

末尾の要素を削除
指定した場所の要素を削除
指定した範囲の複数データを削除する
指定したデータと一致する要素を削除するする
全てのデータを削除する

結合

2つのリストを結合する

応用

複雑な数列も生成できる


昇順にデータをソートする
降順にデータをソートする

多次元リストのソート

1番目の要素でソートする
i番目の要素でソートする
降順にリストを並び替える
【応用】平均でソート

変換

タプルからリストへの変換
リストからタプルへの変換
辞書型をリストに変換する

Python list まとめ【ソート・変換・応用編】

 

ソート

昇順にデータをソートする

sort関数を使用してソートする
list_sample = [2, 9, 3, 7, 4, 1, 0, 6, 8, 5]
list_sample_sorted = list_sample.sort()
print(list_sample)
>>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list_sample_sorted)
>>None

ソートされた関数を出力するsorted関数も存在します.
list_sample = [2, 9, 3, 7, 4, 1, 0, 6, 8, 5]
list_sample_sorted = sorted(list_sample)
print(list_sample)
>>[2, 9, 3, 7, 4, 1, 0, 6, 8, 5]
print(list_sample_sorted)
>>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

文字列もソート可能
list_sample = ['e', 'g', 'c', 'f', 'a', 'b']
list_sample.sort()
print(list_sample)
>>['a', 'b', 'c', 'e', 'f', 'g']


降順にデータをソートする

reverse = Trueにすることで降順ソートができます.
list_sample = [2, 9, 3, 7, 4, 1, 0, 6, 8, 5]
list_sample_sorted = list_sample.sort(reverse = True)
print(list_sample)
>>[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
print(list_sample_sorted)
>>None

sorted関数でも同様.
list_sample = [2, 9, 3, 7, 4, 1, 0, 6, 8, 5]
list_sample_sorted = sorted(list_sample, reverse = True)
print(list_sample_sorted)
>>[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]


多次元リストのソート

1番目の要素でソートする

多次元リストでもソート可能.内部リストの1番目の要素でソートされます
students = [ (3, 'A', 12), (2, 'B', 15), (1, 'B', 10),]
students_sorted = sorted(students)
print(students_sorted)
>>[(1, 'B', 10), (2, 'B', 15), (3, 'A', 12)]

i番目の要素でソートする


内部リストの i 番目の要素でソートしたい場合.比較の際に使用される関数をkeyで指定できる
def func(student_tuple):
    return student_tuple[2]

students = [ (3, 'A', 12), (2, 'B', 15), (1, 'B', 10),]
students_sorted = sorted(students, key=func)
print(students_sorted)
>>[(1, 'B', 10), (3, 'A', 12), (2, 'B', 15)]

labda関数を使えばよりシンプルに書ける.
students = [ (3, 'A', 12), (2, 'B', 15), (1, 'B', 10),]
students_sorted = sorted(students, key=lambda student: student[2])
print(students_sorted)
>>[(1, 'B', 10), (3, 'A', 12), (2, 'B', 15)]


降順にリストを並び替える

reverse関数を使用すれば降順に並び替えができます.
list_sample = [2, 9, 3, 7, 4, 1, 0, 6, 8, 5]
list_sample.reverse()
print(list_sample)
>>[5, 8, 6, 0, 1, 4, 7, 3, 9, 2]


【応用】平均でソート

実装例として生徒の平均点でソートする場合を考えてみる
def func(student_score):
    tmp = sum(student_score[1::])/float(len(student_score)-1)
    return tmp

students = [['name:A', 37, 21, 58, 30, 47], ['name:B', 33, 39, 55, 86, 51], ['name:C', 9, 29, 77, 9, 71]]
students_sorted = sorted(students, key=func)
print(students_sorted)
>>[['name:A', 37, 21, 58, 30, 47], ['name:C', 9, 29, 77, 9, 71], ['name:B', 33, 39, 55, 86, 51]]


変換

タプルからリストへの変換

互いにキャストするだけで変換可能
tuple_sample = ('a', 'b', 'c')
list_sample = list(tuple_sample)
print(list_sample)
>>['a', 'b', 'c']

リストからタプルへの変換

逆も可能
list_sample = ['a', 'b', 'c']
tuple_sample = tuple(list_sample)
print(tuple_sample)
>>('a', 'b', 'c')

辞書型をリストに変換する

こちらも同様にキャストで実装可能です.指定しない場合はkeyがリストとなって出力されます.
dict_sample = {'a': 123, 'b':456, 'c':789}
list_sample = list(dict_sample)
print(list_sample)
>>['a', 'b', 'c']

valueから構成されるリストを取得したい場合はvalue関数を使用します.
dict_sample = {'a': 123, 'b':456, 'c':789}
list_sample = list(dict_sample.values())
print(list_sample)
>>[123, 456, 789]

valueから構成されるリストを取得したい場合はvalue関数を使用します.
dict_sample = {'a': 123, 'b':456, 'c':789}
list_sample = list(dict_sample.values())
print(list_sample)
>>[123, 456, 789]

文字列からリストに変換

文字列もインデックスでリストと同様に要素を獲得できます
str_sample = 'apple'
print(str_sample[0])
>>a

キャストすることでリスト型に変換できます
str_sample = 'apple'
list_sample= list(str_sample)
print(list_sample)
>>['a', 'p', 'p', 'l', 'e']

リストから文字列へ変換

for式を使い変換できます
list_sample = ['a', 'p', 'p', 'l', 'e']
for buf in list_sample: str_sample += buf
print(str_sample)
>>apple

Python list まとめ 【追加・削除・結合編】

 

追加

リストにデータを追加します.データ型はなんでもいいのが便利だ.


末尾にデータを追加する

末尾に要素を追加する場合はappend関数
list_sample = [2, 9, 3, 7, 4, 1, 0, 6, 8, 5]
list_sample.append('a')
print(list_sample)
>>[2, 9, 3, 7, 4, 1, 0, 6, 8, 5, 'a']

list_sample = [2, 9, 3, 7, 4, 1, 0, 6, 8, 5]
list_sample.append([2, 3, 4])
print(list_sample)
>>[2, 9, 3, 7, 4, 1, 0, 6, 8, 5, [2, 3, 4]]


指定した場所にデータを追加する

末尾に要素を追加する場合はinsert関数.insert(i, x)だと,インデックスiを持つ要素の直前にデータxを挿入します.
ただ,insertだとappendより計算量が多い
list_sample = [2, 9, 3, 7, 4, 1, 0, 6, 8, 5]
list_sample.insert(3, 'a')
print(list_sample)
>>[2, 9, 3, 'a', 7, 4, 1, 0, 6, 8, 5]


削除


末尾の要素を削除

pop関数でインデックスを指定しない場合は末尾の要素が削除される.削除されたデータを返り値として返します.
list_sample = [2, 9, 3, 7, 4, 1, 0, 6, 8, 5]
tmp = list_sample.pop()
print(list_sample)
>>[2, 9, 3, 7, 4, 1, 0, 6, 8]

print(tmp)
>>5


指定した場所の要素を削除

del関数を使用して削除
list_sample = [2, 9, 3, 7, 4, 1, 0, 6, 8, 5]
del list_sample[3]
print(list_sample)
>>[2, 9, 3, 4, 1, 0, 6, 8, 5]

pop関数を使用した別実装
list_sample = [2, 9, 3, 7, 4, 1, 0, 6, 8, 5]
list_sample.pop(3)
print(list_sample)
>>[2, 9, 3, 4, 1, 0, 6, 8, 5]

指定した範囲の複数データを削除する

スライスを使用すれば指定された範囲のデータを削除できます.
list_sample = [2, 9, 3, 7, 4, 1, 0, 6, 8, 5]
del list_sample[2:5]
print(list_sample)
>>[2, 9, 1, 0, 6, 8, 5]


指定したデータと一致する要素を削除する

remove関数は指定したデータと一致する最初の要素を削除します.一致するデータがない場合はエラーを吐きます.
list_sample = [4,3,8,5,3,6,1,3,3,9,8,3,6,3]
list_sample.remove(3)
print(list_sample)
>>[4, 8, 5, 3, 6, 1, 3, 3, 9, 8, 3, 6, 3]

list_sample.remove(99)
>>list.remove(x): x not in list


指定したデータと一致する全ての要素を削除する場合.
list_sample = [4,3,8,5,3,6,1,3,3,9,8,3,6,3]
tmp = [buf for buf in list_sample if buf != 3]
print(tmp)
>>[4, 8, 5, 6, 1, 9, 8, 6]


全てのデータを削除する

clearを使用することで全てのデータを削除できます.
list_sample = [2, 9, 3, 7, 4, 1, 0, 6, 8, 5]
list_sample.clear()
print(list_sample)
>>[]


結合


2つのリストを結合する

リストを結合する場合はextend関数
list_sample_A = [2, 9, 3, 7, 4, 1, 0, 6, 8, 5]
list_sample_B = ['a', 'b', 'c']
list_sample_A.extend(list_sample_B)
print(list_sample_A)
>>[2, 9, 3, 7, 4, 1, 0, 6, 8, 5, 'a', 'b', 'c']

+演算子を使った別実装
list_sample_A = [2, 9, 3, 7, 4, 1, 0, 6, 8, 5]
list_sample_B = ['a', 'b', 'c']
list_sample_C = list_sample_A + list_sample_B
print(list_sample_C)
>>[2, 9, 3, 7, 4, 1, 0, 6, 8, 5, 'a', 'b', 'c']


応用編


上手く組み合わせれば1,1,2,1,2,3,1,2,3,4,1,2 ...みたいなリストも生成できる
list_sample = []
for i in range(1, 8):
    list_sample += range(1, i+1)
print(list_sample)
>>[1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7]