我试图在Python 2.7中以这种方式加入两个列表:
a = ['x','y','z']
b = [1,2,3]
,最终结果应为:
c=['x1','y2','z3']
我该怎么做?
答案 0 :(得分:6)
c = [p + str(q) for p, q in zip(a, b)]
答案 1 :(得分:3)
使用string.format
函数更好,而不是连接字符串。您还可以将itertools.starmap
与列表的zip
版本一起使用:
if(isSearching == true){
let contactDict :NSDictionary = self.filteredArray?.object(at: indexPath.row) as! NSDictionary;
let strArray :NSArray = contactDict.object(forKey: kName) as! NSArray
nameString = strArray.componentsJoined(by: "") as! NSMutableString
//nameString = (contactDict.object(forKey: kName) as? String as! NSMutableString)
companyNameString = (contactDict.object(forKey: kCompanyName) as AnyObject).object(at: 0) as? NSString;
designationString = (contactDict.object(forKey: kDesignation) as AnyObject).object(at: 0) as? NSString;
profileImage = contactDict.object(forKey: kProfilePic) as? UIImage;
connectStatus = contactDict.value(forKey: kLinkStatus) as? NSString;
if(profileImage?.accessibilityIdentifier == "Img_placeholder"){
profileImage = nil;
}
或者您可以将它与传说中的列表推导一起用作:
>>> from itertools import starmap
>>> a = ['x','y','z']
>>> b = [1,2,3]
>>> list(starmap("{}{}".format, zip(a, b)))
['x1', 'y2', 'z3']
# Note: `starmap` returns an iterator. If you want to iterate this value
# only once, then there is no need to type-case it to `list`
使用>>> ['{}{}'.format(x, y) for x, y in zip(a, b)]
['x1', 'y2', 'z3']
,您无需明确键入format
到int
。此外,更改列表中所需字符串的格式也更简单。例如:
str
以下是格式>>> ['{} -- {}'.format(x, y) for x, y in zip(a, b)]
['x -- 1', 'y -- 2', 'z -- 3']
列表的通用解决方案:
n
答案 2 :(得分:1)
您也可以使用map
函数根据@ SilverSlash的解决方案尝试这个:
a = ['x','y','z']
b = [1,2,3]
c = list(map(''.join, zip(a, map(str, b))))
print(c)
输出:
['x1', 'y2', 'z3']