结果是python中列表的第二个元素

时间:2016-01-20 06:55:34

标签: python list python-3.x

我有一个清单:

<?php
$text = "brand => toyota,type => suv, color => white";

$array1 = explode(',', $text);
$newArray = array();

for ($i=0; $i < count($array1); $i++) { 
    $array2=explode('=>', $array1[$i]);
    $newArray[$array2[0]] = $array2[1];
}
echo "<pre>";
print_r($newArray);exit;
?>

我想使用x作为第一个元素的变量,结果将是该列表的第二个元素。

list = [['John','Barnes'], ['Bob','Marley'], ['Chris','Brown']]

然后打印第二个元素。任何人都可以帮我吗?

4 个答案:

答案 0 :(得分:4)

该列表可轻松转换为dict。我能想到的最简单的方法:

In [14]: names = dict(list) # first name -> second name

In [15]: x = input('Type the first name: ')
Type the first name: Bob

In [16]: names[x] # search the `names` dictionary and return the second name
Out[16]: 'Marley'

如果您不想将list转换为字典,那么简单的循环就像

x = input('Type the first name: ')
for first, second in list:
    if first == x:
        print(second)
        break

它也可以写成generator expression

In [19]: x = input('Type the first name: ')
Type the first name: Bob

In [20]: next(second for first, second in list if first == x)
Out[20]: 'Marley'

字典查找通常比这更快,如果可以,你应该使用第一个解决方案。

另外,尽量不要使用内置类型的名称(例如list)和函数作为变量名。

答案 1 :(得分:2)

如果那是你想要的:

x= raw_input("Type the first name\n")
print ''.join([i[1] for i in list if i[0] == x ])

输入:

  

约翰

输出:

  

巴恩斯

答案 2 :(得分:0)

IIUC你可以使用re模块和list comprehension

来完成
import re

l = [['John', 'Barnes'], ['Bob', 'Marley'], ['Chris', 'Brown']]
x = 'Bob'

result = [l1[1] for l1 in l if re.findall(x, l1[0])]
print(result)
['Marley']

或者您可以将它与x进行比较:

result = [l1[1] for l1 in l if l1[0] == x]
['Marley']

答案 3 :(得分:0)

这样做的简单方法是:

# It would not be correct to name the list of names as 'list'
l = [['John','Barnes'], ['Bob','Marley'], ['Chris','Brown']]

#get the input and convert it into lowercase
x = input("Type the first name").lower()

#A function that prints the last name , if there is a match , Note : This would also print the last names for all first name matches.
def get_last_names_for_first_names(x):
      for first_name,last_name in l:
         if (first_name.lower() == x):
             print (last_name)

就是这样。