从列表列表中提取项目

时间:2015-11-24 19:23:23

标签: python list

我在python中很新,很难做下一个任务。 我收到一个带有数字和单词none的列表列表,例如:

 [[1,None],[2,4],[1.5,2]]

我的问题是当我通过无(我需要总结列表)时,我需要将其替换为其他列表中相同位置的最大数量。 所以我的结果应该是None = max(4,2)并且收到:

 [[1,4],[2,4],[1.5,2]]

如果我通过for循环,我不明白如何进入其他子列表并检查它们(特别是当我不知道我有多少个子列表时)

7 个答案:

答案 0 :(得分:2)

使用带条件的嵌套列表推导

>>> l =  [[1,None],[2,4],[1.5,2]]
>>> def findMax(j):
...     return max(i[j] for i in l)
... 
>>> [[j if j is not None else findMax(k) for k,j in enumerate(i)] for i in l]
[[1, 4], [2, 4], [1.5, 2]]

此处列表推导检查每个元素是否为None。如果不是,它将打印数字,否则它将达到最大值并打印该元素。

使用map的另一种方法是

>>> l =  [[1,None],[2,4],[1.5,2]]
>>> maxVal = max(map(max, l))
>>> [[j if j is not None else maxVal for k,j in enumerate(i)] for i in l]
[[1, 4], [2, 4], [1.5, 2]]

答案 1 :(得分:1)

这是一个提示:在Python中,for循环迭代遍历某些iterable中的所有元素。如果你有一个列表列表,这意味着列表中的每个元素也可以应用一个for循环,就像for循环中的for循环一样。当且仅当列表的最大深度为2时才能使用此项:

def get_deep_max(deeplst):
   new = []
   for elem in deeplst:
      for num in elem:
         new.append(num)
   return max(new)

尝试编写代码,以便自己替换none值。

答案 2 :(得分:1)

代码:

for idx1, sublist in enumerate(list1):
    for idx2, element in enumerate(sublist):
        if element is None:
          try:
             sublist[idx2] = max(list1[idx1+1])
          except IndexError:
             pass

问题是,如果最后一个列表中有None,则表示您没有指定代码应该执行的操作。我刚刚添加了tryexcept。您可以将pass替换为您希望代码执行的操作。

答案 3 :(得分:1)

我的建议:

 package controllers;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

@WebServlet(description = "A simple database connection", urlPatterns = { "/request" })
public class AddInfo extends HttpServlet {
    private static final long serialVersionUID = 2035938036539261609L;
    private String LOGIN_PAGE = "request.jsp";
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException{ 

            }   
    // Method to handle POST method request.
    @Override
     protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {


         response.setContentType("text/html;charset=UTF-8");
         PrintWriter pw = response.getWriter();


         String con, QueryResult = null;
            DataSource dataSource = null;
            Connection conn = null;
            Statement stmt = null;
            String rs = null;


      try {
            Context initContext = new InitialContext();
            Context envContext = (Context)initContext.lookup("java:/comp/env");
            dataSource = (DataSource)envContext.lookup("jdbc/testdb");
            conn  = dataSource.getConnection();

            String name = request.getParameter("name");  
            String date = request.getParameter("date");  


              PreparedStatement pst = conn.prepareStatement("insert into Campaign values(?,?,?)");

              pst.setInt(1,11);  
              pst.setString(2,name);        
              pst.setString(3,date);


              QueryResult = "Added Information!";

              int i = pst.executeUpdate(); 

              if(i!=0){  
                pw.println("<br>Record has been inserted"); 

                response.sendRedirect(LOGIN_PAGE);
              }  
              else{  
                pw.println("failed to insert the data");  
               }  

            } catch (SQLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (NamingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            try { 
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

    }
}

答案 4 :(得分:1)

from contextlib import suppress


l = [[1,None],[2,4],[1.5,2]]

for sub in l:
    with suppress(ValueError):
        i = sub.index(None)  # find index of None in sublist (or ValueError)
        sub[i] = max(s[i] for s in l if s[i] is not None)  # replace sublist item with max of sublists in same index
        break

print(l)
# [[1, 4], [2, 4], [1.5, 2]]

答案 5 :(得分:1)

这个比其他IMO更清洁阅读

l = [[1,None],[2,4],[1.5,2]]
maxVal = max(map(max, l)) # maps the function 'max' over all the sub-lists
for subl in l:
    for idx,elem in enumerate(subl): # use enumerate to get the index and element
        if elem is None:
            subl[idx] = maxVal
print l
# [[1, 4], [2, 4], [1.5, 2]]

答案 6 :(得分:1)

这是我的建议:

public RationalNumbers(String val){