删除列表中所有列表的最pythonic方法是什么?
例如,如果有一个像[1,2,['randompie'],3,[],4,5]
这样的列表,我该如何制作这样的[1,2,3,4,5]
这是我尝试过的:
[elem for elem in [1,2,['randompie'],3,[],4,5] if type(elem)!='list']
答案 0 :(得分:3)
我会使用列表理解:
import 'dart:async';
import 'package:flutter/material.dart';
void main() {
runApp(new MaterialApp(
home: new Scaffold(
appBar: new AppBar(title: new Text('Example App')),
body: new textList(),
),
));
}
class textList extends StatefulWidget {
@override
State<StatefulWidget> createState() =>
new _textListState();
}
class _textListState extends State<textList>
with TickerProviderStateMixin {
List<Widget> items = new List();
Widget lorem = new textClass("Lorem");
Timer timer;
@override
void initState() {
super.initState();
items.add(new textClass("test"));
items.add(new textClass("test"));
timer = new Timer.periodic(new Duration(seconds: 5), (Timer timer) {
setState(() {
items.removeAt(0);
items.add(lorem);
});
});
}
@override
void dispose() {
super.dispose();
timer.cancel();
}
@override
Widget build(BuildContext context) {
Iterable<Widget> content = ListTile.divideTiles(
context: context, tiles: items).toList();
return new Column(
children: content,
);
}
}
class textClass extends StatefulWidget {
textClass(this.word);
final String word;
@override
State<StatefulWidget> createState() =>
new _textClass();
}
class _textClass extends State<textClass>
with TickerProviderStateMixin {
_textClass();
String word;
Timer timer;
@override
void didUpdateWidget(textClass oldWidget) {
if (oldWidget.word != widget.word) {
word = widget.word;
}
super.didUpdateWidget(oldWidget);
}
@override
void initState() {
super.initState();
word = widget.word;
timer = new Timer.periodic(new Duration(seconds: 2), (Timer timer) {
setState(() {
word += "t";
});
});
}
@override
void dispose() {
super.dispose();
timer.cancel();
}
@override
Widget build(BuildContext context) {
return new Text(word);
}
}
答案 1 :(得分:3)
您可以使用列表推导来轻松过滤列表中的所有非列表元素:
>>> l = [1,2,['randompie'],3,[],4,5]
>>> [el for el in l if not isinstance(el, list)]
[1, 2, 3, 4, 5]
注意我使用了isinstance
而不是type
。这有两个原因。前一个函数是首选,因为it takes parent classes into account。因为isinstance
允许您轻松扩展列表理解以过滤掉其他类型,例如tuple
s或dict
s:
>>> l = [1, 2, ['randompie'], 3, [], 4, 5, (1,)]
>>> [el for el in l if not isinstance(el, (list, tuple))] # filter out tuples and list
[1, 2, 3, 4, 5]