列表理解“ counts [num] = counts.get(num,0)+1”是什么意思?

时间:2020-09-13 18:59:07

标签: python

我知道代码import React, { Component } from 'react'; import './App.css'; import { Navbar, NavbarBrand } from 'reactstrap'; import Menu from './components/MenuComponent'; import DishDetail from './components/DishdetailComponent'; import { DISHES } from './shared/dishes'; class App extends Component { constructor(props){ super(props); this.state = { dishes: DISHES }; } render(){ return( <div> <Navbar dark color="primary"> <div className="container"> <NavbarBrand href="/">Ristorante Con Fusion</NavbarBrand> </div> </Navbar> <DishDetail dishes={this.state.dishes}/> {/* <Menu dishes={this.state.dishes} /> */} </div> ); } } export default App; 是一种列表理解。但是,我不明白这到底是什么意思。任何Python专家都可以向我解释一下吗?

counts[num]=counts.get(num,0)+1

1 个答案:

答案 0 :(得分:2)

列表理解

这不是列表理解。

例如,列出内容:

lst2 = [x for x in lst1 if x % 2 == 0]

lst1是列表,我们仅过滤甚至为if x % 2 == 0的值,并将其分配给列表lst2

counts[num]=counts.get(num,0)+1 的意思

  1. counts.get(num,0)num字典中获得counts键的值,如果键不存在,则返回0
  2. 因此counts[num]=counts.get(num,0)+1将导致counts[num]增加1(如果不存在,则将其设置为1)