我有两个列表,我想以元素方式连接它们。其中一个列表在连接之前经过字符串格式化。
例如:
a = [0, 1, 5, 6, 10, 11]
b = ['asp1', 'asp1', 'asp1', 'asp1', 'asp2', 'asp2']
在这种情况下,a
会受到字符串格式化。也就是说,新的a
或aa
应为:
aa = [00, 01, 05, 06, 10, 11]
最终输出应为:
c = ['asp100', 'asp101', 'asp105', 'asp106', 'asp210', 'asp211']
有人可以告诉我该怎么做?
答案 0 :(得分:38)
使用zip
:
>>> ["{}{:02}".format(b_, a_) for a_, b_ in zip(a, b)]
['asp100', 'asp101', 'asp105', 'asp106', 'asp210', 'asp211']
答案 1 :(得分:15)
使用zip
[m+str(n) for m,n in zip(b,a)]
输出
['asp10', 'asp11', 'asp15', 'asp16', 'asp210', 'asp211']
答案 2 :(得分:8)
其他解决方案(更喜欢 printf formating 样式而不是.format()
用法),它也更小:
>>> ["%s%02d" % t for t in zip(b, a)]
['asp100', 'asp101', 'asp105', 'asp106', 'asp210', 'asp211']
答案 3 :(得分:4)
可以用地图和邮编优雅地完成:
map(lambda (x,y): x+y, zip(list1, list2))
示例:
In [1]: map(lambda (x,y): x+y, zip([1,2,3,4],[4,5,6,7]))
Out[1]: [5, 7, 9, 11]
答案 4 :(得分:1)
不使用zip。我不知道,我认为这是明显的方法。也许我刚开始学习C:)
c=[]
for i in xrange(len(a)):
c.append("%s%02d" % (b[i],a[i]))
答案 5 :(得分:1)
b = ['asp1', 'asp1', 'asp1', 'asp1', 'asp2', 'asp2']
aa = [0, 1, 5, 6, 10, 11]
new_list =[]
if len(aa) != len(b):
print 'list length mismatch'
else:
for each in range(0,len(aa)):
new_list.append(b[each] + str(aa[each]))
print new_list
答案 6 :(得分:0)
输入:
[Serializable]
public partial class SongItem : UserControl,Form
{
private String songName = "Song Name";
private String artistName = "Artist Name";
private Image thumbNail;
private String length;
private int maxLengthSongName = 25;
private int maxLengthArtistName = 25;
private Color colorHoverOn = Color.FromArgb(53,53,53);
private Color colorNormal = Color.FromArgb(53,53,53);
private SongData songData;
public SongItem()
{
InitializeComponent();
this.MouseClick += Control_MouseClick;
MouseEvents(this);
}
private void SongItem_Load(object sender, EventArgs e)
{
try
{
LoadData();
}
catch { }
LoadDataToUI();
}
#region GettersAndSetters
public int MaxLengthSongName
{
get { return maxLengthSongName; }
set { maxLengthSongName = value; }
}
public int MaxLengthArtistName
{
get { return maxLengthArtistName; }
set { maxLengthArtistName = value; }
}
public Color ColorHoverOn
{
get { return colorHoverOn; }
set { colorHoverOn = value; }
}
public Color ColorNormal
{
get { return colorNormal; }
set { colorNormal = value; }
}
public SongData SongData {
get{return songData; }
set { songData = value; }
}
#endregion
public void LoadData()
{
songName = songData.SongName;
artistName = songData.ArtistName;
thumbNail = songData.ThumbNail;
length = songData.Length;
}
void MouseEvents(Control container)
{
foreach (Control c in container.Controls)
{
c.MouseEnter += (s, e) => SongItem_MouseEnter(e);
c.MouseLeave += (s, e) => SongItem_MouseLeave(e);
c.MouseClick += Control_MouseClick;
MouseEvents(c);
};
}
private void SongNameLbl_MouseHover(object sender, EventArgs e)
{
if (songName.Length > maxLengthSongName) {
toolTip1.SetToolTip(songNameLbl, songName);
}
}
private void ArtistNameLbl_MouseHover(object sender, EventArgs e)
{
if (artistName.Length > maxLengthArtistName) {
toolTip1.SetToolTip(artistNameLbl, artistName);
}
}
private void SongNameLbl_Click(object sender, EventArgs e)
{
Clipboard.SetText(artistName + " " +songName);
}
#endregion
#region CurrentlySelected
public event EventHandler<EventArgs> WasClicked;
private void Control_MouseClick(object sender, MouseEventArgs e)
{
var wasClicked = WasClicked;
if (wasClicked != null)
{
WasClicked(this, EventArgs.Empty);
}
IsSelected = true;
}
private bool _isSelected;
public bool IsSelected
{
get { return _isSelected; }
set
{
_isSelected = value;
this.BorderStyle = IsSelected ? BorderStyle.FixedSingle : BorderStyle.None;
}
}
#endregion
private void Fovourite_Click(object sender, EventArgs e)
{
Main newMain = new Main();
// newMain.AddSongToFavorite();
newMain.listBox1.Items.Add("Test");
}
}
输出:
public void AddSongToFavorite() {
listBox1.Items.Add("Test");
//songList2.AddSong("Dire Straits - Sultans Of Swing");
MessageBox.Show("Hello", "Test");
// flowLayoutPanel1.Controls.Add(song);
}
答案 7 :(得分:0)
如果要串联任意数量的列表,可以执行以下操作:
In [1]: lists = [["a", "b", "c"], ["m", "n", "o"], ["p", "q", "r"]] # Or more
In [2]: lists
Out[2]: [['a', 'b', 'c'], ['m', 'n', 'o'], ['p', 'q', 'r']]
In [4]: list(map("".join, zip(*lists)))
Out[4]: ['amp', 'bnq', 'cor']
答案 8 :(得分:0)
我最终使用了一个临时的 DataFrame,它具有可读性和快速性:
a = ["a", "b", "c"]
b = ["1", "2", "3"]
df = pd.DataFrame({"a": a, "b": b})
df["c"] = df.a + df.b
result = df.c.values
输出:
$ result
["a1", "b2", "c3"]
在幕后,DataFrames 使用 numpy,因此结果是高效的。
和函数一样:
import pandas as pd
from typing import List
def _elementwise_concat(self, a: List[str], b: List[str]) -> List[str]:
"""
Elementwise concatenate.
:param a: List of strings.
:param b: List of strings.
:return: List, same length, strings concatenated.
"""
df = pd.DataFrame({"a": a, "b": b})
df["c"] = df.a + df.b
return df.c.values
答案 9 :(得分:0)
列表理解/zip()
/使用zfill()
来格式化。
print ([y+str(x).zfill(2) for x,y in zip(a,b)])
输出:
['asp100', 'asp101', 'asp105', 'asp106', 'asp210', 'asp211']
答案 10 :(得分:0)
使用 Result Price
ID
1 left 100
2 right -10
3 left 60
和 #Full Table with Original Values
df_pivot[result.columns] = result
print(df_pivot)
:
Side left right Result Price
ID
1 100 0 left 100
2 80 90 right -10
3 110 50 left 60
出:
lambda