我有一个函数,它采用的格式如' 1,3-5,7,19'并将输出列表[1, 3, 4, 5, 7, 19]
。
但是,我在想这可能对嵌套列表理解很简单。
我原来的功能是:
result = []
for x in row_range.split(','):
if '-' in x:
for y in range(int(x.split('-')[0]), int(x.split('-')[1]) + 1)):
result.append(y)
else:
result.append(int(x))
我认为理解会是这样的:
result = [y for x in row_range.split(',') if '-' in x else int(x) for y in range(int(x.split('-')[0]), int(x.split('-')[1] + 1)]
甚至
result = [y for x in row_range.split(',') if '-' in x for y in range(int(x.split('-')[0]), int(x.split('-')[1] + 1) else int(x)]
但这些是SyntaxError。将if / else移到理解的前面
result = [y if '-' in x else int(x) for x in row_range.split(',') for y in range(int(x.split('-')[0]), int(x.split('-')[1]) + 1)]
导致IndexError:list index超出范围。
这可能吗?我已经有一个很好地处理它并且更具可读性的函数但我很好奇是否可以在python中完成。
答案 0 :(得分:2)
您可以定义一个小辅助函数:
def foo(x):
x, y = map(int, x.split('-'))
return (x, y + 1)
现在,使用 list comprehension 和嵌套循环。
>>> [y for x in row_range.split(',')
for y in ([int(x)] if '-' not in x else range(*foo(x)))]
[1, 3, 4, 5, 7, 19]
答案 1 :(得分:0)
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JMenuBar mb = new JMenuBar();
mb.add(new JMenu("Test"));
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mb, BorderLayout.NORTH);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
函数的替代解决方案:
re.sub()
输出:
import re
row_range = '1,3-5,7,8,10-14,19' # extended example
cb = lambda r: repr(list(range(int(r.group(1)), int(r.group(2))+1)))[1:-1]
result = [int(i) for i in re.sub(r'(\d+)-(\d+)', cb, row_range).split(',')]
print(result)