我有一个元组列表,例如。
export class AuthGuard implements CanActivate {
constructor(private loggedInService: LoggedinService) {
}
canActivate(next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean{
let url: string = state.url;
return this.checkLogin(url);
}
checkLogin(url: string): boolean {
if (this.loggedInService.isLoggedIn) {
return true;
} else {
this.loggedInService.redirectUrl = url;
return false;
}
}
}
我还有另一个列表
l1 = [(1, 'a', 'x'), (2, 'b', 'y'), (3, 'a', 'z'), (4, 'c', 'xyz')]
我想根据l2 = ['a', 'b', 'c']
中出现的顺序对每个元组的第二个值排序l1
。
最终结果应该是
l2
如您所见,第二个值为l1 = [(1, 'a', 'x'), (3, 'a', 'z'), (2, 'b', 'y'), (4, 'c', 'xyz')]
的元组首先出现,然后是第二个值为a
的元组,最后是具有b
的元组。
我写了以下内容:
c
这很简单。但是我想知道是否有任何pythonic方式可以完成此任务?
答案 0 :(得分:2)
您可以将sorted
与相应的t
函数一起使用:
key
答案 1 :(得分:0)
您可以创建一个使用值作为键的 <%@ Control Language="C#" AutoEventWireup="true" CodeFile="CMSArticleGrid.ascx.cs" Inherits="UserControls_CMS_CMSArticleGrid" %>
<div>
<div class="page-header">
<h1>
Vis nyheter</h1>
</div>
<br />
<div class="grid_top_border">
<asp:DataGrid ID="grdCMS" runat="server" Width="940px" AutoGenerateColumns="false"
OnItemCommand="grdCMS_ItemCommand" AllowPaging="true" AllowSorting="true" OnSortCommand="pageSort"
OnPageIndexChanged="pageChange" PageSize="20" PagerStyle-Mode="NumericPages" OnItemDataBound="item_binding"
PagerStyle-Font-Size="Large" EnableViewState="true">
<HeaderStyle Font-Bold="true" Font-Size="Medium" BackColor="#D0CACD" />
<PagerStyle Mode="NumericPages" Font-Size="Large"></PagerStyle>
<ItemStyle Height="20px" />
<Columns>
<asp:TemplateColumn HeaderText="Artikkeldato" SortExpression="CreatedDate">
<ItemTemplate>
<%#Eval("CreatedDate")%>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Forfatter" SortExpression="Authour">
<ItemTemplate>
<%#Eval("Authour")%>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Brukernavn" SortExpression="UserName">
<ItemTemplate>
<%#Eval("UserName")%>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Godkjent" SortExpression="Verified">
<ItemTemplate>
<%#Eval("Verified")%>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Tittel" SortExpression="Title">
<ItemTemplate>
<asp:Label ID="id" runat="server" Text='<%# Eval("ID") %>' Visible="false"></asp:Label>
<a class="lnkNobb" id="linkAticle" href="CMSArticleList.aspx?ElementId=<%# Eval("ID") %>">
<%# Eval("Title") %></a>
</ItemTemplate>
<%--<ItemTemplate>
<%#Eval("Title")%>
</ItemTemplate>--%>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Kat.Sjef" SortExpression="CatManager">
<ItemTemplate>
<%--<asp:DropDownList ID="ddlprofile" AutoPostBack="true" Width="80px" runat="server">
</asp:DropDownList>--%>
<asp:ListBox ID="lstprofile" runat="server" SelectionMode="Multiple" ToolTip="Press ctrl to select multiple users"></asp:ListBox>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Godkjent">
<ItemTemplate>
<asp:CheckBox ID="cbxVerify" runat="server" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Rediger">
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" CommandName="Edit" CommandArgument='<%#Eval("Id") + "@" +Eval("Verified")%>'
Text="Rediger artikkelen" runat="server"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Slett">
<ItemTemplate>
<asp:LinkButton ID="lnkDelete" CommandName="Delete" CommandArgument='<%#Eval("Id") + "@" +Eval("Verified")%>'
Text="Slett artikkelen" runat="server" OnClientClick="javascript:ConfirmDelete();"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
</div>
<div class="container_24 grid_24">
<asp:Button ID="btnVerify" text="Godkjenne" runat="server" OnClick="btnVerify_click"/>
</div>
<asp:HiddenField ID="hfConfDel" runat="server" />
</div>
and below is my code from code behind:-
protected void Page_Load(object sender, EventArgs e) {
if (Session["User"] == null) {
Response.Redirect("~/Webpages/Info.aspx");
}
if (!IsPostBack) {
BindGrid();
}
}
protected void btnVerify_click(object sender, EventArgs e) {
string userid = ((Session["User"]) as WebUser).UserId.ToString();
// if (userid == "999922" || userid == "999944" || userid == "999945") {
foreach (DataGridItem item in grdCMS.Items) {
CheckBox cbx = (CheckBox)item.FindControl("cbxVerify");
Label id = (Label)item.FindControl("id");
ListBox lstprofile = (ListBox)item.FindControl("lstprofile");
int countSelected = 0;
StringBuilder sb = new StringBuilder();
sb.Append("#");
foreach (ListItem lstitem in lstprofile.Items) {
if (lstitem.Selected) {
countSelected += 1;
sb.Append("" + lstitem.Value + "");
sb.Append("#");
}
}
if (cbx.Checked) {
WebCMS.updateVerified("Y", id.Text, sb.ToString());
} else {
WebCMS.updateVerified("N", id.Text, sb.ToString());
}
Page.ClientScript.RegisterStartupScript(GetType(), "key", "<script>showAlert('Artikkel oppdatert')</script>");
}
BindGrid();
getVerified();
//}else{
// Page.ClientScript.RegisterStartupScript(GetType(), "key", "<script>showAlert('du er ikke autorisert til å godkjenne')</script>");
//}
}
public void BindGrid() {
try {
if (base.Session["User"] is WebUser) {
long userId = (base.Session["User"] as WebUser).UserId;
if ((base.Session["User"] as WebUser).Type == WebUser.UserType.SUPP) {
this.listItem = WebCMS.GetArticlesList((long)Convert.ToInt32((base.Session["User"] as WebUser).UserId.ToString()));
this.grdCMS.Columns[5].Visible = false;
this.grdCMS.Columns[6].Visible = false;
this.btnVerify.Visible = false;
} else {
this.grdCMS.Columns[3].Visible = false;
if ((base.Session["User"] as WebUser).Type == WebUser.UserType.ADMIN) {
this.listItem = WebCMS.GetArticles();
} else {
this.listItem = WebCMS.GetArticlesOfCatChief(userId);
}
}
if ((this.listItem != null) && (this.listItem.Count > 0)) {
this.grdCMS.DataSource = this.listItem;
this.grdCMS.DataBind();
}
this.getVerified();
}
} catch {
}
}
,并使用dict
给出的索引对其进行排序:
enumerate(l2)
以这种方式使用dict的优势在于,不会在每次对l1 = [(1, 'a', 'x'), (2, 'b', 'y'), (3, 'a', 'z'), (4, 'c', 'xyz')]
l2 = ['a', 'b', 'c']
sorting ={key:idx for idx,key in enumerate(l2)}
l3 = sorted(l1, key = lambda x: sorting.get(x[1],9999999999))
print(l3)
的查找中都使用index(...)
。
您将使用l2
来避免丢失键而造成麻烦,并提供一个默认值(确保该值不会出现在列表中),以便将它们放在末尾。
输出:
dict.get()
答案 2 :(得分:-1)
您还可以只使用列表l1
的 sort 方法对每个元组的第二个值进行排序:
l1 = [(1, 'a', 'x'), (2, 'b', 'y'), (3, 'a', 'z'), (4, 'c', 'xyz')]
l1.sort(key=lambda x: x[1])
print(l1)
如果这还不够,并且您需要第二个列表l2
来定义订单,则可以使用列表的 index 方法:
l1 = [(1, 'a', 'x'), (2, 'b', 'y'), (3, 'a', 'z'), (4, 'c', 'xyz')]
l2 = ['a', 'b', 'c']
l1.sort(key=lambda x: l2.index(x[1]))
print(l1)