"TypeError: must be str or None, not list" when trying to pass row from csv.reader to str.split

huangapple go评论57阅读模式
英文:

"TypeError: must be str or None, not list" when trying to pass row from csv.reader to str.split

问题

在CSV文件中,第10列是'DeathCity'。对于CSV文件中的每条记录,如果'DeathCity'列中的城市与用户输入匹配,使用upper()方法进行匹配以避免大小写不一致的问题,请输出该记录。

import csv

city = input("输入一个城市名称:")

f = open("/file.txt")
spamreader = csv.reader(f)

for DeathCity in spamreader:
    if DeathCity[9].strip().upper() == city.upper():
        print("\t".join(DeathCity))

当我尝试根据我的输入来过滤数据时,我一直得到一个错误。

Traceback (most recent call last):
File "hmwk3_1", line 7, in
print("\t".split(DeathCity))
TypeError: must be str or None, not list


<details>
<summary>英文:</summary>

Question:

&gt; The 10-th column of this file is &#39;DeathCity&#39;. For each record in this CSV file, output the record if the city in the DeathCity column matches the user&#39;s input. Use upper() to find the match without issues of different capitalization.

&lt;!-- language: lang-python --&gt;
    import csv

    city = input(&quot;Enter a city name:&quot;)

    f = open(&quot;/file.txt&quot;)
    spamreader=csv.reader(f)

    for DeathCity in spamreader:
        print(&quot;\t&quot;.split(DeathCity))

I keep getting an error when attempting to filter the data based on my input.

    Traceback (most recent call last):
          File &quot;hmwk3_1&quot;, line 7, in &lt;module&gt;
            print(&quot;\t&quot;.split(DeathCity))
    TypeError: must be str or None, not list



</details>


# 答案1
**得分**: 1

如果您查看`csv.reader`的[文档](https://docs.python.org/3/library/csv.html#csv.reader),您会看到您正在迭代字符串列表的行。该列表的每个元素都是一个列,因此使用下标来访问特定列。这就是您应该与用户输入进行比较的字符串。

<details>
<summary>英文:</summary>

If you take a look at the [documentation](https://docs.python.org/3/library/csv.html#csv.reader) for `csv.reader`, you will see that you are iterating over rows that are lists of strings. Each element of that list is a column, so use a subscript to access a specific column. That is the string you should compare to the user input.

</details>



# 答案2
**得分**: 0

你是不是想使用[`str.join`](https://docs.python.org/3/library/stdtypes.html#str.join),而不是[`str.split`](https://docs.python.org/3/library/stdtypes.html#str.split)?

for DeathCity in spamreader:
print("\t".join(DeathCity))


<details>
<summary>英文:</summary>

Did you mean to use [`str.join`](https://docs.python.org/3/library/stdtypes.html#str.join) instead of [`str.split`](https://docs.python.org/3/library/stdtypes.html#str.split)?

for DeathCity in spamreader:
print("\t".join(DeathCity))


</details>



# 答案3
**得分**: -2

只返回翻译好的部分:

如果在打印语句中混合了字符串和变量,必须使用[f-string][1]或等效的方式。例如) `print(f"My name is {variableToPrint}")`

另外,“[split()][2]”函数不接受参数,但要在要拆分的项目上使用点运算符。例如) `DeathCity.split()`

因此,要纠正这两个错误,请尝试以下代码行,看看是否改进了什么。

    print(f"\t{DeathCity.split()}")


<details>
<summary>英文:</summary>

If you mix strings and variables in a print statement, you have to use an [f-string][1], or equivalent. ex) `print(f&quot;My name is {variableToPrint}&quot;)`

Also, the &quot;[split()][2]&quot; function takes no parameters, but is dot-operated on the item you&#39;re wanting to split. ex) `DeathCity.split()`

So, to fix those two errors, try the following line of code and see if it improves anything.

    print(f&quot;\t{DeathCity.split()}&quot;)


  [1]: https://realpython.com/python-f-strings/
  [2]: https://www.w3schools.com/python/ref_string_split.asp

</details>



huangapple
  • 本文由 发表于 2023年2月24日 02:24:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75548851.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定