python试图迭代循环中的关键字

时间:2017-04-26 14:56:31

标签: python dictionary

我正在尝试在dict列表中执行以下操作 - 我正在尝试打印选中的元素== 1.

import { Observable } from 'rxjs/Observable'

export class PlatformMock {
  public ready(): Promise<{String}> {
    return new Promise((resolve) => {
      resolve('READY');
    });
  }

  public registerBackButtonAction(fn: Function, priority?: number): Function {
    return (() => true);
  }

  public hasFocus(ele: HTMLElement): boolean {
    return true;
  }

  public doc(): HTMLDocument {
    return document;
  }

  public is(): boolean {
    return true;
  }

  public getElementComputedStyle(container: any): any {
    return {
      paddingLeft: '10',
      paddingTop: '10',
      paddingRight: '10',
      paddingBottom: '10',
    };
  }

  public onResize(callback: any) {
    return callback;
  }

  get resize(): Observable<any> {
    return Observable.of(true);
  }

  public registerListener(ele: any, eventName: string, callback: any): Function {
    return (() => true);
  }

  public win(): Window {
    return window;
  }

  public raf(callback: any): number {
    return 1;
  }

  public timeout(callback: any, timer: number): any {
    return setTimeout(callback, timer);
  }

  public cancelTimeout(id: any) {
    // do nothing
  }

  public getActiveElement(): any {
    return document['activeElement'];
  }

}

但是我觉得我在循环语法上缺少一些东西,因为它会产生错误信息......任何人都可以帮助我吗?

编辑:收到的错误消息:a = dict(selected= 1, value = 10) b = dict(selected= 0, value= 50) c = dict(selected = 1, value = 150) list_=[a,b,c] for element in list_ if element['selected']: print(element)

2 个答案:

答案 0 :(得分:1)

如果

,你只需将你和你分开
for element in list_:
    if element['selected']:
        print(element)

输出

{'selected': 1, 'value': 10}
{'selected': 1, 'value': 150}

答案 1 :(得分:-1)

你可以简单地写一下这个:

a = dict(selected= 1, value = 10)
b = dict(selected= 0, value= 50)
c = dict(selected = 1, value = 150)
list_=[a,b,c]
for element in [i for i in list_ if i['selected']]:
    print(element)