您好我已经通过Stackoverflow进行了搜索,并且一直在努力解决以下与列表相关的挑战,但作为Python新手,我很难过。
我目前有2个测试数据列表,一个包含用户信息,(新旧用户ID后跟名称数据),另一个列表包含用户和页码(eeIDlist)。我想检查与特定用户关联的页码是否与新ID或旧ID匹配,如果ID匹配,则将页码附加回原始列表。
我已经达到匹配并将列表附加到CompanyName列表,但列表似乎呈指数级增长并代表所有用户页面数据,而不仅仅是与个人关联的页码。
建议热烈欢迎!
我的代码如下:
pagenumbers=[]
for i in CompanyNameList:
for ee in i:
for eeid in eeIDlist:
try:
if (str(eeid[1]) in ee):
pagenumbers.extend([eeid[0]])
i.append(pagenumbers)
i.append([eeid[0]])
except ValueError:
print "Not a valid number"
print i
我的源数据如下:
CompanyNameList:
[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ'],['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ'],['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG'],['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE']]
用户ID和页码 eeIDlist:
[[144128,1],[144138,12],[144130,6],[144131,9],[40013,153],[40074,310],[40023, 210],
[40050,250]]
所需的输出清单:
[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ',[1,153]],
['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ',[6,210]],
['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG',[9,250]],
['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE',[12,310]]]
答案 0 :(得分:1)
您的代码中存在一些错误。
您不需要循环for ee in i
。你想检查一下' 123214' 123214' in
['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ']
,例如123214
,'144128'
,'40013'
和'John'
中的i.append([eeid[0]])
此外,由于您正在处理pagenumbers
,因此您不需要pagenumbers
,这已经足够了;你不希望在你的结果中重复。
此外,for
应附加在CompanyNameList = [
['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ'],
['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ'],
['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG'],
['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE']]
eeIDlist = [[144128,1],
[144138,12],
[144130,6],
[144131,9],
[40013,153],
[40074,310],
[40023, 210],
[40050,250]]
pagenumbers=[]
for i in CompanyNameList:
for eeid in eeIDlist:
try:
# eeid[0] not eeid[1]
if (str(eeid[0]) in i):
# eeid[1] not eeid[0]
pagenumbers.extend([eeid[1]])
except ValueError:
print ("Not a valid number")
i.append(pagenumbers)
pagenumbers = []
print CompanyNameList
循环之外。否则,您将获得多个附加列表。
以下是修复代码错误的代码:
[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ', [1, 153]],
['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ', [6, 210]],
['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG', [9, 250]],
['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE', [12, 310]]]
输出:
public class GlowPanel extends JPanel{
//Attributes
private MouseAdapter repaintAdapter;
private MouseAdapter redispatchAdapter;
private static Color INNER_COLOR = new Color(30, 30, 30, 127);
private static Color OUTER_COLOR = new Color(90, 90, 90, 127);
private static int RADIUS = 25;
private static int DIAMETER = RADIUS * 2;
private Thread glowThread;
private static Point p = new Point(0,0);
private static GlowPanel glowPanel;
private static Boolean MOUSE_LISTEN_STATE = true;
private static Boolean GLOW_THREAD_STATE = false;
private Boolean CURRENT_STATE;
private static ButtonGroup buttonGroup;
//Start Constructor
public GlowPanel(){
//Set Attributes
this.setName("GLOW PANEL");
this.setOpaque(false);
this.setVisible(true);
//this.event
//Add MouseMouseListener
this.repaintAdapter = new RepaintMouseAdapter(this);
this.redispatchAdapter = new RedispatchAdapter();
}
//End Constructor
//Start Methods
/**
* Set state to mouseListen
*/
public synchronized void setStateMouseListen(){
if(!MOUSE_LISTEN_STATE.equals(CURRENT_STATE)){
if(this.glowThread != null){
this.glowThread.interrupt();
}
this.addMouseMotionListener(this.repaintAdapter);
this.addMouseListener(this.redispatchAdapter);
this.addMouseMotionListener(this.redispatchAdapter);
CURRENT_STATE = MOUSE_LISTEN_STATE;
}
}
/**
* Set state to off (don't do any effects)
*/
public synchronized void setStateOff(){
if(this.glowThread != null){
this.glowThread.interrupt();
}
this.removeMouseMotionListener(this.repaintAdapter);
this.removeMouseListener(this.redispatchAdapter);
this.removeMouseMotionListener(this.redispatchAdapter);
CURRENT_STATE = null;
}
/**
* Set state to GlowThread
*/
public synchronized void setStateGlowThread(){
if(!GLOW_THREAD_STATE.equals(CURRENT_STATE)){
this.removeMouseMotionListener(this.repaintAdapter);
this.removeMouseListener(this.redispatchAdapter);
this.removeMouseMotionListener(this.redispatchAdapter);
this.glowThread = new Thread(new Runnable(){
public void run(){
while(!Thread.currentThread().isInterrupted()){
try {
Thread.sleep(1000);
GlowPanel.this.p = MouseInfo.getPointerInfo().getLocation();
SwingUtilities.convertPointFromScreen(p, GlowPanel.this);
GlowPanel.this.repaint();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
});
this.glowThread.start();
CURRENT_STATE = GLOW_THREAD_STATE;
}
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Point p = GlowPanel.this.p;
Shape circle = new Ellipse2D.Double(p.getX() - RADIUS, p.getY() - RADIUS, DIAMETER, DIAMETER);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(GlowPanel.INNER_COLOR);
//g2.fill(circle);
Shape circle2 = new Ellipse2D.Double(p.getX() - RADIUS + 9, p.getY() - RADIUS + 9, DIAMETER - 18, DIAMETER - 18);
//Area a = new Area(circle);
//a.subtract(new Area(circle2));
g2.fill(circle);
g2.setColor(GlowPanel.OUTER_COLOR);
g2.fill(circle2);
}
/**
* Create GUI used to show example
*/
public static void createGUI(){
JFrame jFrame = new JFrame();
//GlowPanel
GlowPanel.glowPanel = new GlowPanel();
//ContentPanel
JPanel contentPanel = new JPanel();
GridBagLayout gBL = new GridBagLayout();
gBL.columnWidths = new int[]{100, 100, 100};
gBL.rowHeights = new int[]{200, 50};
contentPanel.setLayout(gBL);
//Initial Constraints
GridBagConstraints gBC = new GridBagConstraints();
gBC.fill = GridBagConstraints.BOTH;
gBC.gridx = 0;
gBC.gridy = 0;
gBC.weightx = 1;
gBC.weighty = 1;
gBC.gridwidth = 3;
//Hover Panel
JPanel hoverPanel = new JPanel();
hoverPanel.setOpaque(true);
hoverPanel.setBackground(Color.blue);
hoverPanel.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e){}
@Override
public void mousePressed(MouseEvent e){}
@Override
public void mouseReleased(MouseEvent e){}
@Override
public void mouseEntered(MouseEvent e){
hoverPanel.setBackground(Color.yellow);
}
@Override
public void mouseExited(MouseEvent e){
hoverPanel.setBackground(Color.blue);
}
});
contentPanel.add(hoverPanel, gBC);
//Create Buttons
JToggleButton mouseListenButton = new JToggleButton("Mouse Listen");
mouseListenButton.addActionListener(new AbstractAction(){
@Override
public void actionPerformed(ActionEvent e) {
GlowPanel.glowPanel.setStateMouseListen();
}
});
gBC.gridy++;
gBC.weighty = 1;
gBC.gridwidth = 1;
contentPanel.add(mouseListenButton, gBC);
JToggleButton glowThreadButton = new JToggleButton("GlowThread Button");
glowThreadButton.addActionListener(new AbstractAction(){
@Override
public void actionPerformed(ActionEvent e) {
GlowPanel.glowPanel.setStateGlowThread();
}
});
gBC.gridx++;
contentPanel.add(glowThreadButton, gBC);
JToggleButton offButton = new JToggleButton("Off Button");
offButton.addActionListener(new AbstractAction(){
@Override
public void actionPerformed(ActionEvent e) {
GlowPanel.glowPanel.setStateOff();
}
});
gBC.gridx++;
contentPanel.add(offButton, gBC);
GlowPanel.buttonGroup = new ButtonGroup();
GlowPanel.buttonGroup.add(mouseListenButton);
GlowPanel.buttonGroup.add(glowThreadButton);
GlowPanel.buttonGroup.add(offButton);
jFrame.setContentPane(contentPanel);
jFrame.setGlassPane(GlowPanel.glowPanel);
jFrame.getGlassPane().setVisible(true);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.pack();
jFrame.setVisible(true);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
GlowPanel.createGUI();
}
});
}
@Override
public boolean isOptimizedDrawingEnabled(){
return false;
}
//End Methods
public static class RepaintMouseAdapter extends MouseAdapter{
private JComponent jC;
public RepaintMouseAdapter(JComponent jC){
this.jC = jC;
}
@Override
public void mouseMoved(MouseEvent e){
GlowPanel.p = e.getPoint();
this.jC.repaint();
}
}
public static class RedispatchAdapter extends MouseAdapter{
private JComponent lastComponentEntered;
@Override
public void mouseClicked(MouseEvent e){
this.dispatchEvent(e);
}
@Override
public void mousePressed(MouseEvent e){
this.dispatchEvent(e);
}
@Override
public void mouseReleased(MouseEvent e){
this.dispatchEvent(e);
}
@Override
public void mouseEntered(MouseEvent e){
this.dispatchEvent(e);
System.out.println("MOUSE ENTERED");
}
@Override
public void mouseExited(MouseEvent e){
this.dispatchEvent(e);
}
@Override
public void mouseWheelMoved(MouseWheelEvent e){
this.dispatchEvent(e);
}
@Override
public void mouseDragged(MouseEvent e){
this.dispatchEvent(e);
}
@Override
public void mouseMoved(MouseEvent e){
this.dispatchEvent(e);
}
private void dispatchEvent(MouseEvent e) {
Component glass = (Component) e.getSource();
Point glassPanePoint = e.getPoint();
Container container = glass.getParent();
Point containerPoint = SwingUtilities.convertPoint(glass,
glassPanePoint, container);
if (containerPoint.y < 0) { // we're not in the content pane
// Could have special code to handle mouse events over
// the menu bar or non-system window decorations, such as
// the ones provided by the Java look and feel.
} else {
// The mouse event is probably over the content pane.
// Find out exactly which component it's over.
JComponent component = (JComponent) GlowPanel.getDeepestComponentAt(
container, containerPoint.x, containerPoint.y);
//System.out.println(component);
if (component != null) {
// Forward events to component below
Point componentPoint = SwingUtilities.convertPoint(
glass, glassPanePoint, component);
if(e instanceof MouseWheelEvent){
MouseWheelEvent wE = (MouseWheelEvent) e;
component.dispatchEvent(new MouseWheelEvent(component, wE.getID(), wE.getWhen(),
wE.getModifiers(), componentPoint.x, componentPoint.y, wE.getClickCount(),
wE.isPopupTrigger(), wE.getScrollType(), wE.getScrollAmount(), wE.getWheelRotation()));
} else{
component.dispatchEvent(new MouseEvent(component, e
.getID(), e.getWhen(), e.getModifiers(),
componentPoint.x, componentPoint.y, e
.getClickCount(), e.isPopupTrigger()));
}
if(this.lastComponentEntered != null && !this.lastComponentEntered.equals(component)){
System.out.println(!this.lastComponentEntered.equals(component));
}
if(this.lastComponentEntered != null && !this.lastComponentEntered.equals(component)){
e.getComponent().setCursor(component.getCursor());
component.dispatchEvent(new MouseEvent(component, MouseEvent.MOUSE_ENTERED, e.getWhen(),
e.getModifiers(), componentPoint.x, componentPoint.y,
e.getClickCount(), e.isPopupTrigger()));
Point lastComponentPoint = SwingUtilities.convertPoint(
glass, glassPanePoint, this.lastComponentEntered);
this.lastComponentEntered.dispatchEvent(new MouseEvent(this.lastComponentEntered,
MouseEvent.MOUSE_EXITED, e.getWhen(),
e.getModifiers(), lastComponentPoint.x, lastComponentPoint.y,
e.getClickCount(), e.isPopupTrigger()));
}
this.lastComponentEntered = component;
System.out.println(this.lastComponentEntered);
}
}
e.getComponent().repaint();
}
}
public static Component getDeepestComponentAt(Component parent, int x, int y) {
if (!parent.contains(x, y)) {
return null;
}
if (parent instanceof Container) {
Component components[] = ((Container)parent).getComponents();
for (Component comp : components) {
if (comp != null && comp.isVisible() && !(comp instanceof GlowPanel) && !(comp instanceof JLabel)) {
Point loc = comp.getLocation();
if (comp instanceof Container) {
comp = getDeepestComponentAt(comp, x - loc.x, y - loc.y);
} else {
comp = comp.getComponentAt(x - loc.x, y - loc.y);
}
if (comp != null && comp.isVisible()) {
return comp;
}
}
}
}
return parent;
}
答案 1 :(得分:1)
这里有一些代码可以解决这个问题(虽然它不是最多 python ic):
from pprint import pprint as pp
company_name_list = [['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ'],
['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ'],
['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG'],
['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE']]
id_page_list = [[144128, 1],
[144138, 12],
[144130, 6],
[144131, 9],
[40013, 153],
[40074, 310],
[40023, 210],
[40050, 250]]
if __name__ == "__main__":
id_str_page_list = [[str(item[0]), item[1]] for item in id_page_list]
for employee in company_name_list:
pages_list = list()
for id_page in id_str_page_list:
if id_page[0] == employee[0] or \
id_page[0] == employee[1]:
pages_list.append(id_page[1])
if pages_list:
employee.append(pages_list)
pp(company_name_list)
备注强>:
id_str_page
转换为字符串,并使用[Python]: List Comprehensions将其保存到id_str_page_list
,以便立即执行所有转换<强>输出强>:
c:\Work\Dev\StackOverflow\q47257333>"c:\Work\Dev\VEnvs\py35x64_test\Scripts\python.exe" a.py [['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ', [1, 153]], ['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ', [6, 210]], ['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG', [9, 250]], ['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE', [12, 310]]]
答案 2 :(得分:1)
您还可以将 eeIDlist 转换为字典,这样可以更快地搜索它。这也可以让你在一行中执行整个操作:
eeIDdict = dict(eeIDlist)
[j.append([eeIDdict[int(k)] for k in j[0:2]]) for j in CompanyNameList]
现在我们有:
CompanyNameList =
[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ', [1, 153]],
['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ', [6, 210]],
['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG', [9, 250]],
['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE', [12, 310]]]
根据需要。
答案 3 :(得分:1)
我同意罗比的观点,eeIDlist
应该是一个字典......但除此之外,这里是使用您的列表的解决方案。
for c in CompanyNameList:
c.append([
next(e[1] for e in eeIDlist if e[0] == int(c[0])),
next(e[1] for e in eeIDlist if e[0] == int(c[1])),
])
print(c)
将next()
与生成器一起使用意味着只要找到匹配项,列表就会停止搜索。
答案 4 :(得分:1)
我已更正您的代码
CompanyNameList = [['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ'],['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ'],['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG'],['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE']]
eeIDlist = [[144128,1],[144138,12],[144130,6],[144131,9],[40013,153],[40074,310],[40023, 210], [40050,250]]
for CompanyName in CompanyNameList:
pageList = []
newID = int(CompanyName[0])
oldID = int(CompanyName[1])
for eeID in eeIDlist:
if eeID[0] == newID or eeID[0] == oldID:
pageList.append(eeID[1])
CompanyName.append(pageList)
print(CompanyNameList)