我应该创建一个名为['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']
的函数来获取此输入:
[['Len', 'Kate', 'Bob'],['Gerber', 'Fox', 'Dunn']]
然后该函数应该返回一个包含两个名字和姓氏列表的列表,如下所示:
var fruits = [{fruit: "apple", taste: "sour"},
{fruit: "cherry", taste: "sweet", color: "red"}];
functionname(fruits, function(i) { return i.fruit; });
RETURN:
{ "apple": [{fruit: "apple", taste: "sour"}],
{ "cherry": [{fruit: "cherry", taste: "sweet", color: "red"}]
functionname(fruits, function(i) { return i.taste.length; });
RETURN:
{ "4": [{fruit: "apple", taste: "sour"}],
{ "5": [{fruit: "cherry", taste: "sweet", color: "red"}]
我不确定为什么这会给我带来如此多的问题,而且我已经尝试了很多不同的方法来解决它,但我无法得到它。任何帮助表示赞赏。 :)
答案 0 :(得分:1)
首先拆分&剥离项目以获得名称/名字,然后使用listcomps重新组合以获得正确的排列
l = ['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']
c = [[y.strip() for y in x.split(",")] for x in l]
result = [[n[1] for n in c],[n[0] for n in c]]
结果:
[['Len', 'Kate', 'Bob'], ['Gerber', 'Fox', 'Dunn']]
编辑:如果保证分隔为strip
,我们甚至不需要", "
部分,因为split
接受一个多字符串字符串参数。在这种情况下,它甚至更简单:
l = ['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']
c = [x.split(", ") for x in l]
result = [[n[1] for n in c],[n[0] for n in c]]
答案 1 :(得分:1)
利用zip
>>> a = ['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']
>>> b = [i.split(', ') for i in a]
list(zip(*b))
[('Gerber', 'Fox', 'Dunn'), ('Len', 'Kate', 'Bob')]
这将返回元组列表,但如果您真的需要列表,则可以使用map
>>> list(map(list, (zip(*b))))
[['Gerber', 'Fox', 'Dunn'], ['Len', ' Kate', 'Bob']]
如果你想反转刚使用内置reversed
函数
答案 2 :(得分:1)
让Jean-Francois的建议更进一步(顺便说一句,他没有给出这个答案,他是对的)
c = [[y.strip() for y in x.split(",")][::-1] for x in l]
结果是
In [14]: c
Out[14]: [['Len', 'Gerber'], ['Kate', 'Fox'], ['Bob', 'Dunn']]
result = zip(*c)
这是您将来可能会发现有用的更高级的方法
答案 3 :(得分:0)
这也有效:
people = ["Gerber, Len", "Fox, Kate", "Dunn, Bob", "Walsh, Jack"]
def lastfirst(the_list):
name = []
lastname = []
for i in the_list:
lastname.append(i.split(",")[0])
name.append(i.split(", ")[1])
firstlast = [name, lastname]
print (firstlast)
lastfirst(people)
做了一些修正,这条路线更长但可能更适合初学者,至少我会发现它。我意识到输出取决于所观察到的正确形式的输入。
答案 4 :(得分:0)
保持简单并利用列表理解!
def lastfirst(l):
return [[x.split(',')[1].strip() for x in l], [x.split(',')[0].strip() for x in l]]
print lastfirst(['Gerber, Len', 'Fox, Kate', 'Dunn, Bob'])
会打印
[['Len', 'Kate', 'Bob'], ['Gerber', 'Fox', 'Dunn']]
答案 5 :(得分:0)
在Repl中
<img src="<%=Rails.root.join("tmp","image", image.id.to_s)%>" alt=<%= image.name %> >
答案 6 :(得分:-1)
input = ['Gerber, Len', 'Fox, Kate', 'Dunn, Bob']
firsts = []
lasts = []
for i in input:
s = i.split(',')
firsts.append(s[0].strip(' '))
lasts.append(s[1].strip(' '))
result = [lasts,firsts]
print result
结果: -
[['Len', 'Kate', 'Bob'],['Gerber', 'Fox', 'Dunn']]