5

我正在尝试从 python 速成课程中学习 python,但是这一项任务让我很难过,我在任何地方都找不到答案

任务是想想你最喜欢的交通方式,并列出一个存储几个例子的清单 使用你的清单打印一系列关于这些项目的陈述

cars = ['rav4'], ['td5'], ['yaris'], ['land rover tdi'] 

print("I like the "+cars[0]+" ...")

我假设这是因为我有字母和数字,但我不知道如何产生没有错误的结果,并且将不胜感激地收到帮助我得到的错误是

TypeError:只能将str(不是“list”)连接到str**

4

7 回答 7

7
new_dinner = ['ali','zeshan','raza']
print ('this is old friend', new_dinner)

使用逗号,代替加号+

如果你使用加号登录语句,你会得到错误+print ('this is old friend' + new_dinner)

于 2020-05-06T08:19:25.860 回答
4

您的第一行实际上产生了一个列表元组,因此cars[0]是一个列表。

如果你打印cars,你会看到它看起来像这样:

(['rav4'], ['td5'], ['yaris'], ['land rover tdi'])

去掉中间的所有方括号,您将拥有一个可以索引的列表。

于 2019-05-26T11:45:47.593 回答
2

这是您可以用来获得所需结果的可能性之一。它学习导入、使用格式化方法和将数据类型存储在变量中,以及如何将不同的数据类型转换为字符串数据类型!但是您要做的主要事情是将列表或您希望的索引转换为字符串。通过使用str(----)函数。但问题是你已经创建了 4 个列表,你应该只有一个!

from pprint import pprint
cars = ['rav4'], ['td5'], ['yaris'], ['land rover tdi']
Word = str(cars[0])
pprint("I like the {0} ...".format(Word))
于 2019-05-26T11:50:40.033 回答
1

首先,创建一个字符串列表(不是列表元组),然后您可以访问列表的第一个元素(字符串)。

cars = ['rav4', 'td5', 'yaris', 'land rover tdi']
print("I like the "+cars[0]+" ...")

上面的代码输出:I like the rav4 ...

于 2019-05-26T11:53:27.133 回答
0
    new_dinner = ['ali','zeshan','raza']
    print ('this is old friend', str(new_dinner))

    #Try turning the list into a strang only
于 2022-01-15T17:08:38.813 回答
0

你可以这样做

new_dinner = ['ali','zeshan','raza']
print ('this is old friend', *new_dinner)
于 2020-10-13T11:46:06.590 回答
0

这是你的答案:

cars = (['rav4'], ['td5'], ['yaris'], ['land rover tdi']) 

print("I like the "+cars[0][0]+" ...")

我们在这里所做的是先调用列表,然后调用列表中的第一项。由于您将数据存储在元组中,因此这是您的解决方案。

于 2021-04-29T22:40:31.830 回答