结合Python中的元素(Combining elements in Python)
我对Python很陌生,所以也许我偶然发现了答案并没有意识到这一点,但我整天都在搜索和试验代码,我仍然对以下内容感到难过:
给出以下两个列表:
List1 = [1, 2, 3]
List2 = ['a', 'b', 'c']
你会如何创建List3?
List3 = ['1a', '2b', '3c']
I'm very new to Python, so perhaps I stumbled across the answer and didn't realize it, but I have searched and experimented with code all day and I'm still stumped regarding the following:
Given the following two lists:
List1 = [1, 2, 3]
List2 = ['a', 'b', 'c']
How would you create List3?
List3 = ['1a', '2b', '3c']
原文:https://stackoverflow.com/questions/32675350
更新时间:2020-03-04 20:03
最满意答案
['{}{}'.format(a,b) for a,b in zip(list1, list2)]
['{}{}'.format(a,b) for a,b in zip(list1, list2)]
2015-09-20
相关问答
不,不可能。 例: import random
def gen(n):
for i in xrange(n):
if random.randint(0, 1) == 0:
yield i
iterator = gen(10)
iterator长度是未知的,直到你遍历它。 No. It's not possible. Example: import random
def gen(n):
for i in xrange(n):
...
我会让循环范围更小以避免索引超出范围。 因为你不能在任何地方跳到最右边的两个地方,所以没有必要检查这些地方。 这样你就不用担心超出范围。 class Sol(object):
def __init__(self):
self._marker = [
['.', '*', '*', '*'],
['*', '.', '*', '*'],
['*', '*', '.', '*'],
...
我能够使用boost::python::extract( )方法。 I was able to use the boost::python::extract( ) method.
l2 = [','.join(l)]
但是,将此输出包装在列表中没有多大意义。 获取字符串可能更有意义: joined_string = ','.join(l)
l2 = [','.join(l)]
There's not much point to wrapping this output in a list, though. It'd probably make more sense to just get the string: joined_string = ','.join(l)
列表中的+=就地添加运算符与在new_list上调用list.extend()操作new_list 。 .extend()接受一个iterable并将每个元素添加到列表中。 另一方面, list.append()将单个项添加到列表中。 >>> lst = []
>>> lst.extend([1, 2, 3])
>>> lst
[1, 2, 3]
>>> lst.append([1, 2, 3])
>>> lst
[1, 2, 3, [1, 2, 3]]
The += in-place add
...
我将索引从2修改为-1以反映您对“每行上的最后一个元素”的要求,以防每行具有不同数量的元素。 from collections import defaultdict
d = defaultdict(int)
for record in input:
d[record[-1]] += 1
print d
I modified the index from 2 to -1 to reflect your requirement of 'last element on every row' i
...
请检查问题中的列表。我想你忘了第一个元组中的引号(“)。[(”a ^ here,“b”),(“c”,“d”),(“e”,“f “)]我认为这可能会对你有所帮助。 List=[("a","b"),("c","d"),("e","f")]
c=raw_input('ENTER A CHARACTER-')
for i in xrange(len(List)):
if c in List[i]:
ind=List[i].index(c)
print List[i]
...
Python 从左到右存储多个目标的结果,按顺序执行赋值目标表达式。 所以你的第二个版本基本上归结为: temp = list[list.index(max(list))],list[0]
list[0] = temp[0]
list[list.index(max(list))] = temp[1]
请注意, list.index(max(list)) 在 list[0]被更改后执行,这就是您存储最大值的位置。 这在分配报表文档中有记录 : 如果目标列表是以逗号分隔的目标列表:对象必须是具有与目
...
它可能不是最优雅的,但这有效: from collections import defaultdict
a = [1,2,3,4,5]
b = [2,2,5,5,3]
c = [5,2,8,1,1]
d = [1,1,1,1,1]
e = [5,1,2,3,4]
f = [1,1,5,5,5]
all_lists = [a,b,c,d,e,f]
dictionary = defaultdict(list)
for l in all_lists:
dictionary[l[1]].ap
...
['{}{}'.format(a,b) for a,b in zip(list1, list2)]
['{}{}'.format(a,b) for a,b in zip(list1, list2)]